我最近在我的项目中遇到了这个要求,我通过这种方式解决了它。
用于 WPF 的 .NET Core 3.0 中的依赖注入。在解决方案中创建 WPF Core 3 项目后,您需要安装/添加 NuGet 包:
Microsoft.Extensions.DependencyInjection
在我的例子中,我创建了一个名为 LogBase 的类,我想将其用于日志记录,因此在您的 App 类中,添加以下内容(这只是一个基本示例):
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" 使其看起来像这样:
<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:
private readonly ILogBase _log;
public MainWindow(ILogBase log)
{
_log = log;
...etc.. you can use _log over all in this class
在我的 LogBase 类中,我使用我喜欢的任何记录器。
我已经在this GitHub repo 中添加了所有这些。
同时,有人问我如何在用户控件中使用注入。如果有人从中受益,我会提出这个解决方案。检查它here。