如何为 .NET Core 3.0 中 WPF 配置依赖注入 ?
生活随笔
收集整理的這篇文章主要介紹了
如何为 .NET Core 3.0 中 WPF 配置依赖注入 ?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
咨詢區
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.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>接下來我就可以將 ILogBase 注入到構造函數中,如下代碼所示:
private?readonly?ILogBase?_log;public?MainWindow(ILogBase?log) {_log?=?log;...etc..?you?can?use?_log?over?all?in?this?class }完整的代碼,我上傳到了 github:https://github.com/maythamfahmi/WpfSampleDi
點評區
自打.NET Core 面市以來,IOC 逐漸盛行,現在已經很難在代碼中看到 new 了,取而代之的是滿屏的 await,async ????,時代在變,我們也得跟上。
總結
以上是生活随笔為你收集整理的如何为 .NET Core 3.0 中 WPF 配置依赖注入 ?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 巧用Environment.UserIn
- 下一篇: 合肥.NET俱乐部第二期技术沙龙活动预告