使用 Microsoft.Extensions.DependencyInjection 进行依赖注入
没有Unity 的日子,才是好日子~~~~~~~~~~
Using .NET Core 3.0 Dependency Injection and Service Provider with WPF
UPDATE: this article is based on a preview release of .NET Core 3.0. Please refer to Update on using HostBuilder, Dependency Injection and Service Provider with .NET Core 3.0 WPF applications for the latest one.
We all know that .NET Core provides built-in support for Dependency Injection. We typically use it in ASP.NET Core (starting form the ConfigureServices method in the Startup.cs file), but the feature isn’t limited to this framework. So, as .NET Core 3.0 supports also Windows Clients development, we can use it in our WPF and Windows Forms applications.
Let’s see how to do that, for example, in WPF using Visual Studio 2019. Suppose we want to create a service and we also have some application settings; we want to pass both of them to each window of our application via Dependency Injection.
First of all, we must add the required NuGet packages to the project. Right click on the Solution Explorer, select the Manage NuGet Packages command and add the following packages (be sure to select the Include prerelease check):
- Microsoft.Extensions.DependencyInjection
- Microsoft.Extensions.Options.ConfigurationExtensions
- Microsoft.Extensions.Configuration.Json
These packages are necessary to enable Dependency Injection support (the first one) and to store and retrieve application settings in the classic appsettings.json file (the other ones). They will automatically get all the required dependencies.
Then, let’s add a file named appsettings.json to the root folder of the project. Set its Build Action property to Content and Copy to Output Directory to Copy if newer:
1
2
3
4
5
6
7
|
{ "AppSettings" : { "StringSetting" : "Value" , "IntegerSetting" : 42, "BooleanSetting" : true } } |
All the prerequisites are met, so we can start writing our code. Let’s open the App.xaml file and remove the StartupUri property of the Application class. Then, we need to override the OnStartup method in App.xaml.cs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public partial class App : Application { public IServiceProvider ServiceProvider { get ; private set ; } public IConfiguration Configuration { get ; private set ; } protected override void OnStartup(StartupEventArgs e) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile( "appsettings.json" , optional: false , reloadOnChange: true ); Configuration = builder.Build(); var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); ServiceProvider = serviceCollection.BuildServiceProvider(); var mainWindow = ServiceProvider.GetRequiredService<MainWindow>(); mainWindow.Show(); } private void ConfigureServices(IServiceCollection services) { // ... services.AddTransient( typeof (MainWindow)); } } |
In this method we create the Service Provider and configure the IoC container in a similar way of ASP.NET Core. We only need a bit of initialization. First of all, at line 9-13 we create an IConfiguration object that allows to read settings from the appsettings.json file (line 11). Then, we create an instance of a ServiceCollection class that will hold our services. Finally we call the ConfigureServices method (as we have in ASP.NET Core).
Within the latter (lines 24-29), we register all the services used by the application in the exact same way of ASP. NET Core. We’ll complete this method in a moment, but for now let’s notice that we register also the MainWindow class (line 28). This is important because, in this way, the window itself becomes part of the Dependency Injection chain. It means that, after calling this method, at line 20-21 we can get it from the ServiceProvider and then show it. But, more important, it means that we can pass to the MainWindow constructor all the dependencies it needs, as we do for ASP.NET Core Controllers.
Even if the actual services aren’t yet registered, we can run the application and see that everything works as expected.
Now it’s time to complicate the things a bit. First of all, let’s create an AppSettings.cs file to hold configuration settings. This file will map the settings that we write in appsettings.json:
1
2
3
4
5
6
7
8
|
public class AppSettings { public string StringSetting { get ; set ; } public int IntegerSetting { get ; set ; } public bool BooleanSetting { get ; set ; } } |
Then, create also a sample service with its interface:
1
2
3
4
5
6
7
8
9
|
public interface ISampleService { string GetCurrentDate(); } public class SampleService : ISampleService { public string GetCurrentDate() => DateTime.Now.ToLongDateString(); } |
Now we must register these services in the IoC Container, as usual:
1
2
3
4
5
6
7
8
9
|
private void ConfigureServices(IServiceCollection services) { services.Configure<AppSettings> (Configuration.GetSection(nameof(AppSettings))); services.AddScoped<ISampleService, SampleService>(); // ... } |
As said before, the MainWindow itself is in the IoC Container. So, when we get it from the Service Provider, it will automatically be injected with all required services, if any. So, we just need to modify its constructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public partial class MainWindow : Window { private readonly ISampleService sampleService; private readonly AppSettings settings; public MainWindow(ISampleService sampleService, IOptions<AppSettings> settings) { InitializeComponent(); this .sampleService = sampleService; this .settings = settings.Value; } // ... } |
Running this code, we’ll obtain a result like the following:
原文地址:https://www.cnblogs.com/micro-chen/p/11852426.html
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 实例讲解通过PHP创建数据库
- PHP的mysqli_select_db()函数讲解
- PHP的PDO事务与自动提交
- 使用pytorch实现论文中的unet网络
- Python如何优雅删除字符列表空字符及None元素
- php语法检查的方法总结
- PHP实现浏览器格式化显示XML的方法示例
- Laravel框架基于中间件实现禁止未登录用户访问页面功能示例
- PHP的mysqli_stmt_init()函数讲解
- PHP内置函数生成随机数实例
- PHPStudy下如何为Apache安装SSL证书的方法步骤
- PHP的mysqli_thread_id()函数讲解
- thinkPHP框架中layer.js的封装与使用方法示例
- OpenCV+python实现实时目标检测功能
- 在tensorflow实现直接读取网络的参数(weight and bias)的值