Why You Can't Inject Scoped Services in Middleware Constructors (And How to Fix It)
ASP.NET Core middleware is instantiated once at startup, so injecting Scoped services like DbContext in the constructor causes captive dependency—shared instances across requests lead to connection pool exhaustion and data corruption; instead, inject Scoped services via InvokeAsync parameters to get per-request instances.
Reading font

In ASP.NET Core, custom middleware is constructed only once during application startup, effectively behaving as a Singleton. If a Scoped service such as AppDbContext is injected via the middleware constructor, that service gets captured in the root container and reused for every incoming request.
This captive dependency causes two critical problems:
Connection pool exhaustion – the same DbContext instance holds onto database connections across requests.
Data corruption – multiple requests share the same DbContext, leading to entity tracking conflicts and stale data.
Incorrect: Constructor Injection of Scoped Service
public class MyMiddleware {
private readonly RequestDelegate _next;
private readonly AppDbContext _dbContext; // ❌ Scoped service
public MyMiddleware(RequestDelegate next, AppDbContext dbContext) {
_next = next;
_dbContext = dbContext; // Captured at startup
}
}Correct: Inject Scoped Service in InvokeAsync
public async Task InvokeAsync(HttpContext context, AppDbContext dbContext) {
// dbContext is Scoped – a new instance per request
var data = await dbContext.Users.ToListAsync();
await _next(context);
}The InvokeAsync method executes once per request. The framework resolves the AppDbContext parameter from the current request's DI scope, ensuring each request receives its own isolated instance.
This pattern is a frequent interview question because it tests understanding of DI lifecycles (Singleton vs. Scoped vs. Transient) and how middleware fits into the request pipeline.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.