.NET点滴:说说Middleware构造中获取不到Scoped服务的问题

时间:2022-12-04 12:54:36

  “为什么中间件的构造函数里不能使用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);
}
}

看报错:

.NET点滴:说说Middleware构造中获取不到Scoped服务的问题

  但如果把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的生命周期类型啊?”的答案。

  想要更快更方便的了解相关知识,可以关注微信公众号 

.NET点滴:说说Middleware构造中获取不到Scoped服务的问题