当前位置:网站首页>定制.NET 6.0的依赖注入
定制.NET 6.0的依赖注入
2022-07-30 10:33:00 【dotNET跨平台】
本章是《定制ASP NET 6.0框架系列文章》的第三篇。在本章,我们将学习ASP.NET Core的依赖项注入(DI)以及如何自定义它。
我们将讨论以下主题:
使用不同的DI容器
探索ConfigureServices方法
使用其他的ServiceProvider
Scrutor简介
技术准备
我们使用以下命令(你可以在console, shell,或Bash终端),创建一个MVC应用:
dotnet new mvc -n DiSample -o DiSample在Visual Studio中打开项目,或在控制台中键入以下命令,在Visual Studio Code中打开项目:
cd DiSample
code .使用不同的DI容器
在大多数项目中,我们其实不需要使用不同的DI容器。ASP.NET Core中的现有DI基本上满足我们的需要。但是,你可能喜欢其他DI容器的其他功能:
使用
Ninject创建一个支持模块作为轻量级依赖项的应用程序。比如,您可能希望将模块放入特定目录中,并在应用程序中自动注册这些模块。在应用程序外部的配置文件中,比如,在XML或JSON文件中,而不是仅在C#中配置服务。这是各种DI容器中的常见功能,但
ASP.NET Core中尚不支持。在运行时添加服务,获取动态的DI容器,这也是一些DI容器中的常见特性。
现在,让我们看看ConfigureServices方法是如何操作的。
探索ConfigureServices方法
我们将当前的ConfigureServices方法与以前的长期支持版本(TLS)进行比较,看看有什么变化。如果您使用版本3.1创建的ASP.NET Core项目,并打开Startup.cs文件,配置服务的方法如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
});
services.AddControllersWithViews();
services.AddRazorPages();
}相反,在 ASP.NET Core 6.0,没有启动Startup.cs,服务的配置在Startup.cs中进行,如下所示:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container. builder.Services.AddControllersWithViews();
var app = builder.Build();
// The rest of the file isn't relevant for this chapter这两种情况都可以获得IServiceCollection,其中默认已经填充了ASP.NET Core所需的一组服务,比如宿主服务、ConfigureServices方法之前执行的相关服务。
以上方法中,添加了更多的服务。
首先,将包含
cookie策略选项的配置类添加到ServiceCollection。AddMvc()方法添加MVC框架所需的服务。
到目前为止,我们有大约140个服务注册到IServiceCollection。
但是,服务集合不是实际的DI容器,真实的DI容器被包装在所谓的服务提供者中(ServiceProvider)。
那么应该如何获取DI容器呢?
IServiceCollection有了一个扩展方法,它用于从服务集合中创建IServiceProvider,代码如下:
IServiceProvider provider = services.BuildServiceProvider()ServiceProvider包含不可变容器,即在运行时无法更改。在ConfigureServices方法执行后,会在后台创建IServiceProvider。
接下来,我们再看下如何在DI定制过程中,替代IServiceProvider。
使用其他IServiceProvider
如果其他容器已经支持ASP.NET Core,则更改为其他或自定义DI容器将变得非常容易。通常,第三方DI容器会使用IServiceCollection做为自己的容器,它通过循环集合将已注册的服务移动到另一个容器。
我们用第三方容器Autofac举个例子。在命令行中键入以下命令,加载NuGet包:
dotnet add package Autofac.Extensions.DependencyInjection要注册自定义IoC容器,通常需要注册不同的IServiceProviderFactory,IServiceProviderFactory将创建一个ServiceProvider实例。如果第三方容器支持ASP.NET Core,则必须提供一个该工厂类。如果你要使用Autofac,则需要使用AutofacServiceProviderFactory。
我们在Program.cs中给IHostBuilder编写一个扩展方法,内部注册一个AutofacServiceProviderFactory:
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace DiSample;
public static class IHostBuilderExtension { public static IHostBuilder UseAutofacServiceProviderFactory(this IHostBuilder hostbuilder)
{
hostbuilder.UseServiceProviderFactory (new AutofacServiceProviderFactory()); return hostbuilder;
}
}注意,不要忘记将引入名称空间:Autofac和Autofac.Extensions.DependencyInjection。
要使用此扩展方法,可以在Program.cs中使用AutofacServiceProvider:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseAutofacServiceProviderFactory();
// Add services to the container. builder.Services.AddControllersWithViews();以上通过扩展方法将AutofacServiceProviderFactory添加到IHostBuilder中,并启用AutofacIoC容器。后续会转而使用Autofac向IServiceCollection添加服务。
再强调一下,除非必要。通常,我们不一定要替换现有的.NET CoreDI容器。
Scrutor简介
在本章的开头,我提到了服务的自动注册,这里可以通过其他DI容器完成。这里介绍一个名为Scrutor的不错的NuGet包来实现。Scrutor通过向.NET Core DI容器向IServiceCollection添加一个扩展方法,用以自动注册服务。
扩展阅读
这里介绍一篇关于Scrutor的非常详细的博客文章,建议您继续阅读这篇文章以了解更多信息。
回顾
通过以上演示,我们将能够使用任何.NET标准兼容的DI容器替换现有容器。如果您选择的容器不包括ServiceProvider,请自己实现一个IServiceProvider接口,并在其中使用DI容器。如果您选择的容器没有提供填充服务的方法,请自行创建自己的方法。循环已注册的服务并将其添加到另一个容器中。
最后一步听起来很简单,实现起来比较费劲,因为需要将所有的IServiceCollection注册转换为其他容器的注册,它的复杂性取决于其他DI容器的实现细节。
任何时候,我们都可以选择使用任何与.NET标准兼容的DI容器,替换ASP.NET Core中的许多默认实现。
在下一章我们将探讨如何以不同的方式配置HTTPS,感谢您的阅读。
边栏推荐
- Log4j additivity属性简介说明
- 4、yolov5-6.0 ERROR: AttributeError: ‘Upsample‘ object has no attribute ‘recompute_scale_factor‘ 解决方案
- PyQt5 - draw text on window
- vscode中写markdown格式笔记的配置过程和相关语法
- OC-ARC (Automatic Reference Counting) automatic reference counting
- WARN: Establishing SSL connection without server's identity verification is not recommended when connecting to mysql
- Meikle Studio - see the actual combat notes of Hongmeng equipment development five - drive subsystem development
- Scrapy crawler website image crawling
- 从数据流中快速查找中位数
- Re20:读论文的先例:普通法的信息理论分析
猜你喜欢

Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解

图像去噪——Neighbor2Neighbor: Self-Supervised Denoising from Single Noisy Images
![【 HMS core 】 【 Analytics Kit] [FAQ] how to solve the payment amount in huawei pay analysis shows zero problem?](/img/f3/b9256fc04d1c9e15c74d2fc14db0fb.png)
【 HMS core 】 【 Analytics Kit] [FAQ] how to solve the payment amount in huawei pay analysis shows zero problem?

Multithreading--the usage of threads and thread pools

Meikle Studio - see the actual combat notes of Hongmeng equipment development five - drive subsystem development

易基因:人类tRNA基因位点表现出与衰老相关的DNA高甲基化|研究文章

Re15: Read the paper LEVEN: A Large-Scale Chinese Legal Event Detection Dataset

从数据流中快速查找中位数

Nacos configuration in the project of battle

第3章 信息收集
随机推荐
Detailed explanation of JVM memory layout, class loading mechanism and garbage collection mechanism
BERT pre-training model series summary
Re15: Read the paper LEVEN: A Large-Scale Chinese Legal Event Detection Dataset
360发布面向未来的EDR,全方位守护政企用户终端安全
Study Notes 10--Main Methods of Local Trajectory Generation
JSP 语法简介说明
自适应控制——仿真实验一 用李雅普诺夫稳定性理论设计自适应规律
SST-Calib: A lidar-visual extrinsic parameter calibration method combining semantics and VO for spatiotemporal synchronization calibration (ITSC 2022)
In the robot industry professionals, Mr Robot industry current situation?
mysql与redis 区别
vscode中写markdown格式笔记的配置过程和相关语法
AB测试 总结归纳
In 2022, the top will be accepted cca shut the list
Selected System Design | Design of CAN Bus Controller Based on FPGA (with Code)
ospf2 two-point two-way republish (question 2)
OC-手动引用计数内存管理
Quick Start Tutorial for flyway
WARN: Establishing SSL connection without server's identity verification is not recommended when connecting to mysql
【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出
(BUG record) No module named PIL