有高并发 高访问量网站开发,做购物网站能否生存,正规游戏代理平台,百度网站如何做咨询区 user842818#xff1a;我非常熟悉 ASP.NET Core 和它开箱即用的依赖注入支持#xff0c;当 Controller 需要依赖注入时#xff0c;可以在 构造函数 中以参数的形式来实现#xff0c;这个IOC的理念相当好#xff0c;我想把它带到 WPF 中#xff0c;当我同样以构造函… 咨询区 user842818我非常熟悉 ASP.NET Core 和它开箱即用的依赖注入支持当 Controller 需要依赖注入时可以在 构造函数 中以参数的形式来实现这个IOC的理念相当好我想把它带到 WPF 中当我同样以构造函数的方式进行注入却无法实现。请问我该如何修改让 WPF 支持呢我真的很喜欢IOC。回答区 maytham-ɯɐɥʇʎɐɯ我最近在一个项目也需要实现这个功能我是这样实现的。首先需要创建一个 WPF Core 3 的项目然后从 nuget 上安装依赖包: Microsoft.Extensions.DependencyInjection在我的项目中我创建了一个 LogBase 类用来记录日志这里我就拿它来做例子。
private readonly ServiceProvider _serviceProvider;public App()
{var serviceCollection new ServiceCollection();ConfigureServices(serviceCollection);_serviceProvider serviceCollection.BuildServiceProvider();
}private void ConfigureServices(IServiceCollection services)
{services.AddSingletonILogBase(new LogBase(new FileInfo($C:\temp\log.txt)));services.AddSingletonMainWindow();
}private void OnStartup(object sender, StartupEventArgs e)
{var mainWindow _serviceProvider.GetServiceMainWindow();mainWindow.Show();
}然后在 App.xaml 中添加 StartupOnStartup 比如下面这样
Application x:ClassVaultDataStore.Wpf.Appxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:localclr-namespace:VaultDataStore.WpfStartupOnStartupApplication.Resources/Application.Resources
/Application接下来我就可以将 ILogBase 注入到构造函数中如下代码所示
private readonly ILogBase _log;public MainWindow(ILogBase log)
{_log log;...etc.. you can use _log over all in this class
}完整的代码我上传到了 githubhttps://github.com/maythamfahmi/WpfSampleDi点评区 自打.NET Core 面市以来IOC 逐渐盛行现在已经很难在代码中看到 new 了取而代之的是满屏的 awaitasync ????时代在变我们也得跟上。