在 ASP.NET 5 中请求范围内的服务
Request Scoped Services in ASP.NET 5
我正在努力让服务的范围限定为 ASP.NET 中的当前请求 5。我的启动代码如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMyService, MyService>();
}
public void Configure(IApplicationBuilder app)
{
app.UseRequestServices();
app.UseMiddleware<MyMiddleware>();
}
public class MyMiddleware
{
RequestDelegate _next;
IMyService MyService;
public MyMiddleware(RequestDelegate next, IMyService myService)
{
_next = next;
MyService = myService;
}
public async Task Invoke(HttpContext context)
{
--> Here - context.RequestServices does not contain myService
}
}
传递给 MyMiddleware 构造函数的 IMyService 似乎不是请求范围的。它不是按请求处理的,在调用中间件时它没有在 HttpContext.RequestServices
.
中注册
我好像漏掉了什么明显的东西?
好的,以更简单的形式写出代码后,我意识到问题所在。
中间件不是 transient/scoped,因此需要在 Invoke 方法而不是中间件的构造函数上传递范围内的依赖项。
public class MyMiddleware
{
RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IMyService myService)
{
--> Now working. MyService is registered on context.RequestServices
}
}
我正在努力让服务的范围限定为 ASP.NET 中的当前请求 5。我的启动代码如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMyService, MyService>();
}
public void Configure(IApplicationBuilder app)
{
app.UseRequestServices();
app.UseMiddleware<MyMiddleware>();
}
public class MyMiddleware
{
RequestDelegate _next;
IMyService MyService;
public MyMiddleware(RequestDelegate next, IMyService myService)
{
_next = next;
MyService = myService;
}
public async Task Invoke(HttpContext context)
{
--> Here - context.RequestServices does not contain myService
}
}
传递给 MyMiddleware 构造函数的 IMyService 似乎不是请求范围的。它不是按请求处理的,在调用中间件时它没有在 HttpContext.RequestServices
.
我好像漏掉了什么明显的东西?
好的,以更简单的形式写出代码后,我意识到问题所在。
中间件不是 transient/scoped,因此需要在 Invoke 方法而不是中间件的构造函数上传递范围内的依赖项。
public class MyMiddleware
{
RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IMyService myService)
{
--> Now working. MyService is registered on context.RequestServices
}
}