dotnetcore3.1 WPF 中使用依賴注入
Intro
在 ASP.NET Core 中默認就已經集成了依賴注入,最近把 DbTool 遷移到了 WPF dotnetcore 3.1,
在 WPF 中我們也希望能夠使用依賴注入,下面來介紹一下如何在 WPF dotnetcore3.1 中使用依賴注入
App.xaml 配置
- 打開
App.xaml
文件,刪除 StartupUri 配置,StartupUri="MainWindow.xaml"
- 打開 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;
}
// ...
}