Can I add a new scoped service within a custom middleware?

烂漫一生 提交于 2019-12-06 09:27:54

First add your scoped service in your ConfigureServices(IServiceCollection services)

services.AddScoped<IMyService, MyService>();

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);
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!