我可以在自定义中间件中添加新的作用域服务吗? [英] Can I add a new scoped service within a custom middleware?
问题描述
我在Asp .Net Core中使用WebApi,我想知道是否/如何添加新的作用域服务,以便所有后续的中间件和控制器都可以通过依赖注入来访问?还是应该与HttpContext.Items共享状态?因为HttpContext在WebApi控制器中根本不可用,所以这似乎不是它的预期目的.
I'm using WebApi in Asp .Net Core and I'm wondering if/how I can add a new scoped service that all following middleware and controllers can get access to through dependency injection? Or should I share state with HttpContext.Items instead? That doesn't seem to be what it is intended for since HttpContext isn't available at all in a WebApi-controller?
如果HttpContext或DI都不是正确的工具,那么如何在不从头开始创建状态的情况下,在请求管道中传播状态呢?
If neither HttpContext or DI is the right tool for this, then how can I propagate state in the request-pipeline without having it already created from the beginning?
推荐答案
首先在您的ConfigureServices(IServiceCollection服务)中添加您的作用域服务
First add your scoped service in your ConfigureServices(IServiceCollection services)
services.AddScoped<IMyService, MyService>();
然后,我知道将范围服务注入到中间件中的唯一方法就是将其注入到Middlware的Invoke方法中
Then, the only way I know of to get a scoped service injected into your middleware is to inject it into the Invoke method of your Middlware
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext, IMyService service)
{
service.DoSomething();
await _next(httpContext);
}
}
默认情况下,注入MyMiddleware的构造函数会使它成为单例,因为它仅在启动时被调用.每次都会调用Invoke,并且依赖项注入将获取作用域对象.
Injecting in the constructor of MyMiddleware will make it a singleton by default as it's only called on startup. Invoke is called every time and dependency injection will grab the scoped object.
这篇关于我可以在自定义中间件中添加新的作用域服务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!