WPF的.NET Core 3.0中的依赖项注入 [英] Dependency Injection in .NET Core 3.0 for WPF
问题描述
我对ASP.NET Core和对依赖项注入的支持非常熟悉.控制器可以通过在其构造函数中添加参数来要求依赖关系.如何在WPF UserControls中实现依赖关系?我尝试向构造函数添加参数,但这没用.我喜欢IOC的概念,希望将其推广到WPF.
I’m quite familiar with ASP.NET Core and the support for dependency injection out of the box. Controllers can require dependencies by adding a parameter in their constructor. How can dependencies be achieved in WPF UserControls? I tried adding a parameter to the constructor, but that didn’t work. I love the IOC concept and would prefer to bring this forward to WPF.
推荐答案
我最近在我的项目中遇到了这一要求,并以此方式解决了该问题.
I have recently come across this requirement to my project and I solved it this way.
用于WPF的.NET Core 3.0中的依赖项注入.在解决方案中创建WPF Core 3项目后,需要安装/添加NuGet软件包:
For Dependency Injection in .NET Core 3.0 for WPF. After you create a WPF Core 3 project in your solution, you need to install/add NuGet packages:
Microsoft.Extensions.DependencyInjection
在我的情况下,我创建了一个称为LogBase的类,我想将其用于日志记录,因此在您的App类中添加以下内容(是的,这只是一个基本示例):
In my case, I created a class called LogBase that I want to use for logging, so in your App class, add the following (and ya this is just a basic example):
private readonly ServiceProvider _serviceProvider;
public App()
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
_serviceProvider = serviceCollection.BuildServiceProvider();
}
private void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILogBase>(new LogBase(new FileInfo($@"C:\temp\log.txt")));
services.AddSingleton<MainWindow>();
}
private void OnStartup(object sender, StartupEventArgs e)
{
var mainWindow = _serviceProvider.GetService<MainWindow>();
mainWindow.Show();
}
在您的App.xaml中,添加Startup ="OnStartup"所以看起来像这样:
In your App.xaml, add Startup="OnStartup" so it looks like this:
<Application x:Class="VaultDataStore.Wpf.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:VaultDataStore.Wpf"
Startup="OnStartup">
<Application.Resources>
</Application.Resources>
</Application>
因此,在MainWindow.xaml.cs中,您将ILogBase注入到构造函数中,如下所示:
So in your MainWindow.xaml.cs, you inject ILogBase in the constructor like this:
private readonly ILogBase _log;
public MainWindow(ILogBase log)
{
_log = log;
...etc.. you can use _log over all in this class
在LogBase类中,我以自己喜欢的方式使用任何记录器.
In my LogBase class, I use any logger I like in my way.
我在此GitHub存储库中将所有这些内容加在一起.
I have added all this together in this GitHub repo.
同时,有人问我如何在用户控件中使用注入.如果有人从中受益,我想出了一种解决方案.在此处进行检查.
Meanwhile, I have been asked how to use injection inside user control. I come up with this solution if some one get the benefit of it. Check it here.
这篇关于WPF的.NET Core 3.0中的依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!