6

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?

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?

4

1 回答 1

15

首先在您的 ConfigureServices(IServiceCollection services) 中添加您的范围服务

services.AddScoped<IMyService, MyService>();

然后,我知道将作用域服务注入中间件的唯一方法是将其注入中间件的 Invoke 方法

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 并且依赖注入将获取作用域对象。

于 2017-03-23T18:57:56.837 回答