Can I add a new scoped service within a custom middleware?
Asked Answered
S

1

11

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?

Signature answered 23/3, 2017 at 18:22 Comment(0)
D
33

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.

Dissyllable answered 23/3, 2017 at 18:57 Comment(3)
I tried this, but scope is ignored (even when set to Singleton, DoSomething called every request).Averett
@Averett Have you fixed that?Varro
@DmytroKryvoruchenko, no, I never got back to it (pet project).Averett

© 2022 - 2024 — McMap. All rights reserved.