当前位置:网站首页>.NET点滴:说说Middleware构造中获取不到Scoped服务的问题
.NET点滴:说说Middleware构造中获取不到Scoped服务的问题
2022-04-23 03:02:00 【dotNET跨平台】
今天小桂问我:“为什么中间件的构造函数里不能使用scope的生命周期类型啊?”,
那就用实例来得到答案吧,先看小桂说的情况,是报错的:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<ITestService, TestService>();
var app = builder.Build();
app.UseMiddleware<TestMiddleware>();
app.MapGet("/djy", () =>
{
Console.WriteLine("打酱油!");
return "OK";
});
app.Run();
public interface ITestService
{
void Print();
}
public class TestService : ITestService
{
public TestService()
{
Console.WriteLine($"Time:{DateTime.Now},ToDo:TestService.ctor");
}
public void Print()
{
Console.WriteLine($"Time:{DateTime.Now},ToDo:TestService.Print");
}
}
public class TestMiddleware
{
private readonly RequestDelegate _next;
private readonly ITestService _testService;
//正确姿势
//public TestMiddleware(RequestDelegate next)
public TestMiddleware(RequestDelegate next, ITestService testService)
{
Console.WriteLine($"Time:{DateTime.Now},ToDo:TestMiddleware.ctor");
_next = next;
_testService = testService;
}
//正确姿势
//public async Task InvokeAsync(HttpContext context, ITestService testService)
public async Task InvokeAsync(HttpContext context)
{
_testService.Print();
await _next(context);
}
}
看报错:
但如果把Service注入换成AddTransient就没有问题,这是为什么呢?
官网有一段话:“Middleware is constructed at app startup and therefore has application life time. Scoped lifetime services used by middleware constructors aren't shared with other dependency-injected types during each request. ……”,这段话挑重点,就是中间件是服务启动时初始化,整个生命周期构造只调用一次,而AddScoped是每个对象实例化,DI就会创建一份,可以说Scoped的颗粒度更小,所以就不能在中件间的构造函数中出现(构造只有在初始化的时候调用到)。所以Scoped的Service放在InvokeAsync的参数中,因为InvokeAsync是每次请求时才调用到,和Scoped的颗粒度是一样的,所以这就是:“为什么中间件的构造函数里不能使用scope的生命周期类型啊?”的答案。
版权声明
本文为[dotNET跨平台]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sd7o95o/article/details/124310725
边栏推荐
- Chapter IV project cost management of information system project manager summary
- Introduction to ACM [inclusion exclusion theorem]
- Linux redis - redis database caching service
- Linux redis - redis ha sentinel cluster construction details & redis master-slave deployment
- Redis data server / database / cache (2022)
- First knowledge of C language ~ branch statements
- 【Hcip】OSPF常用的6种LSA详解
- Use of MySQL command line client and common commands
- Kubernetes study notes
- Summary of interface automation interview questions for software testing
猜你喜欢
How to build an integrated industrial Internet plus hazardous safety production management platform?
Leangoo brain map - shared multi person collaborative mind mapping tool
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
Solve the problem that PowerShell mining occupies 100% of cpu7 in win7
tf. keras. layers. Timedistributed function
Android 高阶面试必问:全局业务和项目的架构设计与重构
Kubernetes study notes
基于ele封装下拉菜单等组件
Innovation and management based on Scrum
Plug in for vscode
随机推荐
Binary tree
Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)
Log cutting - build a remote log collection server
Summary of interface automation interview questions for software testing
Niuke white moon race 6 [solution]
Android 高阶面试必问:全局业务和项目的架构设计与重构
《信息系统项目管理师总结》第七章 项目沟通管理
The space between the left and right of the movie ticket seats is empty and cannot be selected
Classification and regression tree of machine learning
MySQL complex query uses temporary table / with as (similar to table variable)
Summary of software test interview questions
When using art template inheritance, compileerror: invalid or unexpected token generated
JS relearning
Liunx foundation - zabbix5 0 monitoring system installation and deployment
Traversal of l2-006 tree (middle and later order determination binary tree & sequence traversal)
The interface request takes too long. Jstack observes the lock holding
c#可变参数params的介绍
Configuring Apache Web services for servers such as Tianyi cloud
Development notes of raspberry pie (12): start Advantech industrial control raspberry pie uno-220 Kit (I): introduction and operation of the system
tf. keras. layers. MaxPooling? D function