当前位置:网站首页>定制.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,感谢您的阅读。
边栏推荐
- 易基因:人类tRNA基因位点表现出与衰老相关的DNA高甲基化|研究文章
- Linux内核设计与实现(十)| 页高速缓存和页回写
- IP池设计思考(面试点)[通俗易懂]
- 【HMS core】【Analytics Kit】【FAQ】如何解决华为分析付费分析中付款金额显示为0的问题?
- 分页 paging
- Database dirty reads, non-repeatable reads, phantom reads and corresponding isolation levels
- SST-Calib:结合语义和VO进行时空同步校准的lidar-visual外参标定方法(ITSC 2022)
- OC-ARC(Automatic Reference Counting)自动引用计数
- In 2022, the top will be accepted cca shut the list
- jmeter接口压力测试(一)
猜你喜欢

The configuration process and related syntax of writing markdown format notes in vscode

零代码开发入门:快速上手DIY函数公式的5个步骤

实现web实时消息推送的7种方案

STM32CubeMX configuration to generate FreeRTOS project

电压跟随器不要随便加

Re16: Read the paper ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation

Paper reading: SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers

Matplotlib--plot markers

Flink_CDC construction and simple use

360发布面向未来的EDR,全方位守护政企用户终端安全
随机推荐
4. yolov5-6.0 ERROR: AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' solution
AB测试 总结归纳
In the robot industry professionals, Mr Robot industry current situation?
Security思想项目总结
自适应控制——仿真实验一 用李雅普诺夫稳定性理论设计自适应规律
kubernetes的一些命令
死锁的理解
Materialist Dialectics - Conditionalism
Security Thought Project Summary
易基因:人类tRNA基因位点表现出与衰老相关的DNA高甲基化|研究文章
从数据流中快速查找中位数
Re16: Read the paper ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation
PyQt5 - draw sine curve with pixels
鸿湖万联扬帆富设备开发板正式合入OpenHarmony主干
【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1
【HMS core】【Analytics Kit】【FAQ】如何解决华为分析付费分析中付款金额显示为0的问题?
[100个Solidity使用技巧]1、合约重入攻击
flowable workflow all business concepts
Flask's routing (app.route) detailed
Meikle Studio - see the actual combat notes of Hongmeng equipment development five - drive subsystem development