当前位置:网站首页>. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
2022-04-23 03:06:00 【Dotnet cross platform】
Xiao Gui asked me today :“ Why can't we use... In the constructor of middleware scope Life cycle type of ?”,
Then use examples to get the answer , Let's look at what Xiao Gui said first , It's the wrong report :
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<ITestService, TestService>();
var app = builder.Build();
app.UseMiddleware<TestMiddleware>();
app.MapGet("/djy", () =>
{
Console.WriteLine(" get some soy sauce !");
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;
// Correct posture
//public TestMiddleware(RequestDelegate next)
public TestMiddleware(RequestDelegate next, ITestService testService)
{
Console.WriteLine($"Time:{DateTime.Now},ToDo:TestMiddleware.ctor");
_next = next;
_testService = testService;
}
// Correct posture
//public async Task InvokeAsync(HttpContext context, ITestService testService)
public async Task InvokeAsync(HttpContext context)
{
_testService.Print();
await _next(context);
}
}
Reading newspapers is wrong :
But if you take Service Injection replacement AddTransient There is no problem , Why is that ?
There is a passage on the official website :“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. ……”, Pick the point of this passage , The middleware is initialized when the service is started , The entire lifecycle construct is called only once , and AddScoped Is the instantiation of each object ,DI Will create a , so to speak Scoped The particle size is smaller , So it can't appear in the constructor between middleware ( The construct can only be called when initializing ). therefore Scoped Of Service Put it in InvokeAsync The parameters of the , because InvokeAsync Is called every time a request is made , and Scoped The particle size is the same , So this is :“ Why can't we use... In the constructor of middleware scope Life cycle type of ?” The answer .
版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230301333754.html
边栏推荐
- REINFORCE
- Source code interpretation of Flink index parameters (read quantity, sent quantity, sent bytes, received bytes, etc.)
- 使用栈来解决”迷你语法分析器“的问题
- Numpy stack function
- Middle and rear binary tree
- Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
- Er and eer models
- 准备一个月去参加ACM,是一种什么体验?
- SQL statement - DDL
- svg标签中利用<polygon/>循环数组绘制多边形
猜你喜欢
The backtracking of stack is used to solve the problem of "the longest absolute path of file"
Guangcheng cloud service can fill in a daily report regularly every day
The most detailed in the whole network, software testing measurement, how to optimize software testing cost and improve efficiency --- hot
Passing object type parameters through openfeign
Judge whether there is a leap year in the given year
再战leetcode (290.单词规律)
C# 读写二进制文件
Ningde's position in the times is not guaranteed?
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
Niuke white moon race 6 [solution]
随机推荐
樹莓派開發筆記(十二):入手研華ADVANTECH工控樹莓派UNO-220套件(一):介紹和運行系統
Laravel8- use JWT
TP5 inherits base and uses the variables in base
C#语法糖空合并运算符【??】和空合并赋值运算符【 ??=】
Introduction and use of openfeign component
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (9)
Close the computer port
微软是如何解决 PC 端程序多开问题的
MYSQL_ From mastery to abandonment
【鉴权/授权】自定义一个身份认证Handler
TP5 customization in extend directory succeeded and failed. Return information
最通俗易懂的依赖注入之生命周期
Openfeign service call
腾讯视频VIP会员,周卡特价9元!腾讯官方直充,会员立即生效!
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
tf. keras. layers. Timedistributed function
Numpy append function
.NET7之MiniAPI(特别篇):.NET7 Preview3
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
Opencv combines multiple pictures into video