码迷,mamicode.com
首页 > Windows程序 > 详细

dotnetcore3.1 WPF 中使用依赖注入

时间:2020-04-17 09:52:20      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:info   transient   require   etc   new   cep   protect   col   netcore   

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

dotnetcore3.1 WPF 中使用依赖注入

标签:info   transient   require   etc   new   cep   protect   col   netcore   

原文地址:https://www.cnblogs.com/dearroy/p/12717388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!