加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

dotnetcore3.1 WPF 中使用依赖注入

发布时间:2020-12-16 09:02:48 所属栏目:asp.Net 来源:网络整理
导读:dotnetcore3.1 WPF 中使用依赖注入 Intro 在 ASP.NET Core 中默认就已经集成了依赖注入,最近把 DbTool 迁移到了 WPF dotnetcore 3.1, 在 WPF 中我们也希望能够使用依赖注入,下面来介绍一下如何在 WPF dotnetcore3.1 中使用依赖注入 App.xaml 配置 打开 Ap

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

  • https://www.cnblogs.com/hippieZhou/p/10637348.html
  • https://github.com/WeihanLi/DbTool/tree/wpf-dev/DbTool

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读