dotnetcore3.1 WPF 中使用依赖注入

时间:2023-03-09 15:40:51
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

相关文章