.NET中Middleware如何解决Scoped服务获取失败的问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计797个文字,预计阅读时间需要4分钟。
为什么在中间件的构造函数中不能使用`scope`的生命周期类型呢?
因为中间件的构造函数是在依赖注入容器创建时调用的,此时还没有开始作用域(scope)的生命周期。`scope`的生命周期类型是在请求开始时创建的,用于管理请求相关的服务实例。如果在中间件的构造函数中使用`scope`的生命周期类型,那么在构造函数执行时,这些服务实例还未创建,会导致错误。
以下是一个示例,展示了如何正确地在中间件中使用服务:
csharppublic class MyMiddleware{ private readonly RequestDelegate _next; private readonly IMyService _myService;
public MyMiddleware(RequestDelegate next, IMyService myService) { _next=next; _myService=myService; }
public async Task InvokeAsync(HttpContext context) { // 使用_myService await _next(context); }}
public void ConfigureServices(IServiceCollection services){ services.AddMyService(); services.AddControllers();}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
app.UseRouting();
app.UseEndpoints(endpoints=> { endpoints.MapControllers(); });
app.UseMiddleware();}
在这个示例中,`IMyService`是通过依赖注入容器提供的,而不是在中间件的构造函数中直接创建的。这样,`IMyService`的生命周期将与中间件的生命周期保持一致,确保在中间件中可以安全地使用它。
“为什么中间件的构造函数里不能使用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的生命周期类型啊?”的答案。
想要更快更方便的了解相关知识,可以关注微信公众号
本文共计797个文字,预计阅读时间需要4分钟。
为什么在中间件的构造函数中不能使用`scope`的生命周期类型呢?
因为中间件的构造函数是在依赖注入容器创建时调用的,此时还没有开始作用域(scope)的生命周期。`scope`的生命周期类型是在请求开始时创建的,用于管理请求相关的服务实例。如果在中间件的构造函数中使用`scope`的生命周期类型,那么在构造函数执行时,这些服务实例还未创建,会导致错误。
以下是一个示例,展示了如何正确地在中间件中使用服务:
csharppublic class MyMiddleware{ private readonly RequestDelegate _next; private readonly IMyService _myService;
public MyMiddleware(RequestDelegate next, IMyService myService) { _next=next; _myService=myService; }
public async Task InvokeAsync(HttpContext context) { // 使用_myService await _next(context); }}
public void ConfigureServices(IServiceCollection services){ services.AddMyService(); services.AddControllers();}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
app.UseRouting();
app.UseEndpoints(endpoints=> { endpoints.MapControllers(); });
app.UseMiddleware();}
在这个示例中,`IMyService`是通过依赖注入容器提供的,而不是在中间件的构造函数中直接创建的。这样,`IMyService`的生命周期将与中间件的生命周期保持一致,确保在中间件中可以安全地使用它。
“为什么中间件的构造函数里不能使用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的生命周期类型啊?”的答案。
想要更快更方便的了解相关知识,可以关注微信公众号

