Explore Library
Code QuizAdvanced

Scoped Service in Middleware Constructor

Spotting a captive dependency bug when injecting a scoped service into custom middleware.

Codecsharp
public class AuditMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IUserContext _userContext; // registered as Scoped

    public AuditMiddleware(RequestDelegate next, IUserContext userContext)
    {
        _next = next;
        _userContext = userContext;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _userContext.Track(context.Request.Path);
        await _next(context);
    }
}

// Program.cs
builder.Services.AddScoped<IUserContext, UserContext>();
app.UseMiddleware<AuditMiddleware>();

What is the bug in this middleware code?