How to do DI in asp.net core middleware?

UserManager<ApplicationUser> is (by default) registered as a scoped dependency, whereas your CreateCompanyMiddleware middleware is constructed at app startup (effectively making it a singleton). This is a fairly standard error saying that you can’t take a scoped dependency into a singleton class.

The fix is simple in this case – you can inject the UserManager<ApplicationUser> into your Invoke method:

public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
{
    await _next.Invoke(context);
}

This is documented in ASP.NET Core Middleware: Per-request middleware dependencies:

Because middleware is constructed at app startup, not per-request, scoped lifetime services used by middleware constructors aren’t shared with other dependency-injected types during each request. If you must share a scoped service between your middleware and other types, add these services to the Invoke method’s signature. The Invoke method can accept additional parameters that are populated by DI:

Leave a Comment