zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Go反射原理
    并发控制--context篇
    Go并发控制--WaitGroup篇
    Go依赖管理--module
    正睿培训 8.4 学习笔记
    bitset
    7.18 学习笔记
    7.17 学习笔记
    P6835 [Cnoi2020]线形生物
    UVA11300 Spreading the Wealth 思维题
  • 原文地址:https://www.cnblogs.com/weihanli/p/12366166.html
Copyright © 2011-2022 走看看