网站建站平台排行榜,cute主题破解版WordPress,个人养老保险12000元,可以做用户画像的网站今天小桂问我#xff1a;“为什么中间件的构造函数里不能使用scope的生命周期类型啊#xff1f;”#xff0c;那就用实例来得到答案吧#xff0c;先看小桂说的情况#xff0c;是报错的#xff1a;var builder WebApplication.CreateBuilder(args);builder.Services.AddS… 今天小桂问我“为什么中间件的构造函数里不能使用scope的生命周期类型啊”那就用实例来得到答案吧先看小桂说的情况是报错的var builder WebApplication.CreateBuilder(args);builder.Services.AddScopedITestService, TestService();
var app builder.Build();app.UseMiddlewareTestMiddleware();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 arent shared with other dependency-injected types during each request. ……”这段话挑重点就是中间件是服务启动时初始化整个生命周期构造只调用一次而AddScoped是每个对象实例化DI就会创建一份可以说Scoped的颗粒度更小所以就不能在中件间的构造函数中出现构造只有在初始化的时候调用到。所以Scoped的Service放在InvokeAsync的参数中因为InvokeAsync是每次请求时才调用到和Scoped的颗粒度是一样的所以这就是“为什么中间件的构造函数里不能使用scope的生命周期类型啊”的答案。