In ASP.NET Core, why does injecting a scoped DbContext into a convention-based middleware's constructor go wrong, and where should it go instead?
answer
- constructed once, from the root provider
- ValidateScopes on in Development
- Cannot resolve scoped service from root provider
- elsewhere: one context shared by all requests
- take it as an InvokeAsync parameter
basics
~20 sConvention middleware is built once from the root provider. In Development scope validation throws when the pipeline is built; elsewhere one DbContext is captured and shared by every request. Take the DbContext as an InvokeAsync parameter, or use IMiddleware.
solid answer
~40 s`UseMiddleware<T>()` creates the convention class once, when the pipeline is built, with `ActivatorUtilities` over `app.ApplicationServices`, the root provider. A `DbContext` registered by `AddDbContext` is scoped. In Development, `WebApplicationBuilder` turns on `ValidateScopes`, so building the pipeline throws `InvalidOperationException` ("Cannot resolve scoped service ... from root provider") and the app fails to start. In other environments the root provider hands out one instance that lives until shutdown, shared by every concurrent request: EF Core throws when it detects two requests using it at once, and its change tracker keeps growing. The fix is to declare the context as an extra `InvokeAsync` parameter, resolved per request from `HttpContext.RequestServices`, the same instance the endpoint receives, or to make the class an `IMiddleware` registered as scoped or transient.
code
csharp · 24 linespublic sealed class TenantResolutionMiddleware(RequestDelegate next)
{
// Wrong: TenantResolutionMiddleware(RequestDelegate next, StorefrontDbContext db)
// Right: take the scoped context per request
public async Task InvokeAsync(HttpContext context, StorefrontDbContext db, ITenantContext tenant)
{
var brand = await db.Brands.AsNoTracking()
.SingleOrDefaultAsync(b => b.Host == context.Request.Host.Host, context.RequestAborted);
if (brand is null)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
tenant.Set(brand.Id, brand.Name);
await next(context);
}
}
// Program.cs
// builder.Services.AddDbContext<StorefrontDbContext>(...);
// builder.Services.AddScoped<ITenantContext, TenantContext>();
// app.UseMiddleware<TenantResolutionMiddleware>();go deeper
Remember the rule: scoped services such as a DbContext go on InvokeAsync, not in a convention middleware's constructor.
Explain when the middleware is constructed, which provider resolves constructor and InvokeAsync parameters, and why Development throws while production does not.
Diagnose the production symptoms of a captured context (concurrent-use exceptions, growing memory, stale data) and pick between InvokeAsync parameters and IMiddleware.
Set guardrails such as scope validation in test environments and review checklists so captured scoped services are caught before production.
## Two providers, two moments ASP.NET Core resolves services from two places: - the **root provider** (`app.Services`, also `IApplicationBuilder.ApplicationServices`), which lives as long as the app; - a **request scope**, created per request and exposed as `HttpContext.RequestServices`, which is disposed when the response completes. A scoped service, such as a `DbContext` added with `AddDbContext` (scoped by default), is meant to be resolved from a request scope, so each request gets its own instance. Convention-based middleware is activated at a different moment. When the host starts, the pipeline is built, and `UseMiddleware<T>()` calls `ActivatorUtilities.CreateInstance(app.ApplicationServices, ...)` **once**. The constructor's dependencies therefore come from the root provider, before any request exists. ## What happens in each environment | Environment | Provider setting | Result of a scoped `DbContext` in the constructor | |---|---|---| | Development | `ValidateScopes = true` (set by `WebApplicationBuilder`) | `InvalidOperationException`: "Cannot resolve scoped service 'StorefrontDbContext' from root provider." while the pipeline is built, so the app does not start | | other environments | no scope validation | the root provider creates one `DbContext` that lives until shutdown and is shared by every request | The second row is the dangerous one, because it passes every test that runs in a single thread: 1. Two concurrent requests use the same context; when EF Core detects the overlap it throws an `InvalidOperationException` ("A second operation was started on this context instance before a previous operation completed."). 2. The change tracker keeps every entity the context has tracked until it is disposed, so memory grows and later queries can return stale tracked instances. 3. The context, and its connection, is disposed only when the app stops. 4. The middleware and the endpoint see **different** contexts, so work the middleware does is not part of the endpoint's unit of work. ## The fix: per-request parameters Convention middleware supports extra parameters on `InvokeAsync`. `UseMiddleware` resolves them on every call from `context.RequestServices`, the request scope: ```csharp public sealed class TenantResolutionMiddleware(RequestDelegate next) { public async Task InvokeAsync(HttpContext context, StorefrontDbContext db, ITenantContext tenant) { // db and tenant are this request's scoped instances await next(context); } } ``` The endpoint, a controller or any service resolved later in the same request receives the **same** `StorefrontDbContext` and `ITenantContext` instances, which is exactly what tenant resolution needs: the middleware records the tenant in a scoped `ITenantContext`, and everything downstream reads it. If a parameter's service is not registered, the call fails per request with `InvalidOperationException` ("Unable to resolve service for type ... while attempting to Invoke middleware ..."). The alternative is `IMiddleware`: register the middleware class itself as scoped or transient, and the per-request `IMiddlewareFactory` resolves it from the request scope, so its constructor may take scoped services. ## What the constructor may take - **Singletons**: `IOptions<T>`, `IOptionsMonitor<T>`, `ILogger<T>`, `IHttpClientFactory` and your own singleton services. - **Plain values** passed through `UseMiddleware<T>(args)`. - **Not** scoped services, and not transient services that themselves depend on scoped ones. - **Not** `IOptionsSnapshot<T>`, which is scoped; use `IOptionsMonitor<T>` when the middleware must see reloaded configuration. ## Catching it before production Because the failure only shows when scope validation is on, make sure it is on wherever the pipeline is exercised: - Run integration tests and local debugging in the Development environment, where `WebApplicationBuilder` already sets `ValidateScopes` and `ValidateOnBuild`. - Turn validation on explicitly for a staging environment with `builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });`, accepting a small startup cost. - In review, treat any constructor parameter of a convention middleware that is not a singleton, an options accessor or a plain value as a defect. - Prefer giving the middleware an `ITenantContext`-style scoped holder through `InvokeAsync` rather than letting it cache tenant data in fields, which would leak one brand's data into another brand's requests. ## Why it is an interview favourite The bug is invisible in code review unless you know when middleware is constructed, it is silent in production, and the Development exception names the root provider rather than the middleware. A candidate who explains the activation moment, the two providers and the `InvokeAsync` fix has shown the mental model the interviewer is testing.
- Why does the constructor version crash in Development but appear to work in production?`WebApplicationBuilder` enables `ValidateScopes` (and `ValidateOnBuild`) only in Development. With validation, resolving a scoped service from the root provider throws while the pipeline is built. Without it, the root provider silently creates one long-lived instance that every request shares.
- Do the middleware and the endpoint get the same DbContext when it is an InvokeAsync parameter?Yes. `UseMiddleware` resolves `InvokeAsync` parameters from `HttpContext.RequestServices`, the request scope, which is the same scope that supplies the endpoint's or controller's dependencies later in that request.
- Could the constructor take IServiceScopeFactory and create its own scope instead?It compiles, but every scope you create yields a different `DbContext` from the one the endpoint gets, and you must dispose the scope yourself. For per-request work the `InvokeAsync` parameter is simpler and shares the request's instance.
- Scoped services in a middleware constructor are re-created for every request.
- AddDbContext registers the context as a singleton, so constructor injection is fine.
- The Development exception means the DbContext was never registered.
- Wrapping the injected DbContext in a using block fixes the captured instance.
- InvokeAsync parameters are resolved from the root provider once, at startup.