dotnetcore3.1 WPF 中使用依賴注入


dotnetcore3.1 WPF 中使用依賴注入

Intro

在 ASP.NET Core 中默認就已經集成了依賴注入,最近把 DbTool 遷移到了 WPF dotnetcore 3.1,
在 WPF 中我們也希望能夠使用依賴注入,下面來介紹一下如何在 WPF dotnetcore3.1 中使用依賴注入

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 的構造方法中注入我們所需要的服務即可

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

        _localizer = localizer;
    }
    // ...
}

Reference


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM