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

  • 相关阅读:
    Iconfont在Vue中的使用
    yarn安装依赖报错
    动漫
    伤痛的魅力。绷带男子特辑
    记STM32F103C8T6+STLINK下载器在Keil中的设置
    JQuery浮动对象插件
    树莓派RTL8723BU_LINUX驱动安装
    python虚拟环境相关设置备忘
    解决树莓派控制台命令行乱码
    python模块wifi使用小记
  • 原文地址:https://www.cnblogs.com/weihanli/p/12366166.html
Copyright © 2011-2022 走看看