dotnetcore3.1 WPF 中使用依賴注入

dotnetcore3.1 WPF 中使用依賴注入

Intro

在 ASP.NET Core 中默認就已經集成了依賴注入,最近把 DbTool 遷移到了 WPF dotnetcore 3.1,
在 WPF 中咱們也但願可以使用依賴注入,下面來介紹一下如何在 WPF dotnetcore3.1 中使用依賴注入html

App.xaml 配置

  1. 打開 App.xaml 文件,刪除 StartupUri 配置, StartupUri="MainWindow.xaml"
  2. 打開 App.xaml.cs 重載 OnStartup 方法,在 OnStartup 中添加本身的初始化代碼,在初始化代碼中註冊本身的服務註冊 MainWindow,並在最後從服務中獲取 MainWindow 服務,並調用 window 的 Show 方法
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        Init();
        base.OnStartup(e);
    }

    private void ConfigureServices(IServiceCollection services)
    {
        services.TryAddTransient<MainWindow>();
        services.AddJsonLocalization(options => options.ResourcesPathType = ResourcesPathType.CultureBased);
    }

    private void Init()
    {
        #region Init Settings

        var settings = new SettingsViewModel();
        settings.ConnectionString = settings.DefaultConnectionString;
        // set current culture
        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(settings.DefaultCulture);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(settings.DefaultCulture);

        #endregion Init Settings

        IServiceCollection services = new ServiceCollection();
        ConfigureServices(services);

       services.BuildServiceProvider()
            .GetRequiredService<MainWindow>()
            .Show();
    }
}

MainWindow

因爲 MainWindow 上面咱們已經修改成經過依賴注入來獲取,因此咱們能夠在 MainWindow 的構造方法中注入咱們所須要的服務便可git

public partial class MainWindow: Window
{
    private readonly IStringLocalizer<MainWindow> _localizer;
    public MainWindow(
        IStringLocalizer<MainWindow> localizer)
    {
        InitializeComponent();

        _localizer = localizer;
    }
    // ...
}

Reference

相關文章
相關標籤/搜索