skip to content

In an ASP.NET Core 10 gym-booking API, a singleton ClassScheduleCache injects BookingDbContext; why does startup fail in Development, what happens in Production, and how do you fix it?

level: seniorimportance: should knowfreq 55%

answer

  1. captive scoped dependency
  2. ValidateScopes and ValidateOnBuild in Development
  3. inner "Cannot consume scoped service" message
  4. resolved from the root provider in Production
  5. AddDbContextFactory or IServiceScopeFactory

basics

~10 s

The singleton captures a scoped context. In Development WebApplicationBuilder validates scopes during Build() and throws; in Production nothing checks, so one context serves every request. Fix it with AddDbContextFactory or a scope per operation.

solid answer

~50 s

`ClassScheduleCache` is registered with `AddSingleton`, but `AddDbContext` made `BookingDbContext` scoped, so the singleton would hold one request's context forever. In Development, `WebApplicationBuilder` builds the container with `ValidateScopes` and `ValidateOnBuild` set to `true`, so `builder.Build()` throws an `AggregateException` ("Some services are not able to be constructed") whose inner `InvalidOperationException` says it cannot consume the scoped `BookingDbContext` from the singleton. In Production neither check runs: the context is resolved from the root provider, lives until shutdown, and is shared by concurrent requests, which yields `InvalidOperationException` about a second operation on the context, stale tracked data and a growing change tracker. I fix it by registering `AddDbContextFactory<BookingDbContext>` and injecting `IDbContextFactory<BookingDbContext>`, creating a short-lived context with `await using` per refresh, or by creating a scope with `IServiceScopeFactory.CreateAsyncScope()`. If the cache does not need to be a singleton, making it scoped is simpler still.

code

csharp · 5 lines
csharp
builder.Services.AddDbContextFactory<BookingDbContext>(o =>
    o.UseNpgsql(builder.Configuration.GetConnectionString("Bookings")));

// factory: Singleton; BookingDbContext itself: Scoped (registered by the factory call)
builder.Services.AddSingleton<ClassScheduleCache>();

go deeper

for a junior

Know that a singleton must not inject a DbContext registered with AddDbContext, and that the Development startup error is warning you about exactly that.

for a middle

Explain ValidateScopes and ValidateOnBuild, why they run only in Development, and why the captured context is resolved from the root provider elsewhere.

for a senior

Diagnose the production symptoms, concurrency exceptions, stale reads and memory growth, back to a captured context, and choose between a scoped consumer, AddDbContextFactory and a manual scope.

for a principal

Decide how the team keeps captive contexts out of production, for example by enabling build-time validation in CI tests and reviewing every singleton that touches data.

## The defect A **captive dependency** is a longer-lived service holding a shorter-lived one. With EF Core in ASP.NET Core it almost always looks like this: ```csharp builder.Services.AddDbContext<BookingDbContext>(o => o.UseNpgsql(builder.Configuration.GetConnectionString("Bookings"))); builder.Services.AddSingleton<ClassScheduleCache>(); public class ClassScheduleCache(BookingDbContext db) // scoped captured by singleton { public Task<List<GymClass>> TodayAsync() => db.GymClasses.Where(c => c.StartsAt.Date == DateTime.UtcNow.Date).ToListAsync(); } ``` `AddDbContext` registers the context **Scoped**; `AddSingleton` asks the container to build `ClassScheduleCache` once for the life of the app. The cache would therefore keep whichever context it received first, forever. ## Development: the container refuses to build When the environment is Development, `WebApplicationBuilder` creates the service provider with `ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }`. Two checks follow: 1. **ValidateOnBuild** walks every registration during `builder.Build()` and tries to construct its call site, so the problem surfaces at startup rather than on the first request. 2. **ValidateScopes** rejects any singleton whose dependency graph contains a scoped service, and any scoped service resolved directly from the root provider. Together they make `builder.Build()` throw an `AggregateException` ("Some services are not able to be constructed") before the app accepts a single request. Its inner `InvalidOperationException` names the descriptor and carries the core message, of the form "Cannot consume scoped service 'BookingDbContext' from singleton 'ClassScheduleCache'" (with full type names). That error is a gift: it is the cheapest moment to catch the bug. ## Production: it runs, then fails under load Outside Development the default provider is built without those checks. The singleton resolves `BookingDbContext` from the **root** provider, so the context effectively becomes a singleton too. What follows: - **Concurrency exceptions.** Two requests hitting `TodayAsync` at once use one non-thread-safe context; EF Core throws `InvalidOperationException` ("A second operation was started on this context instance before a previous operation completed"), or, if it misses the overlap, behaves unpredictably. - **Stale data.** The identity map hands back entities tracked hours ago, so a class that filled up still shows free seats. - **Memory growth.** Every tracked entity stays in the change tracker for the life of the process. - **Poisoned state.** A failed `SaveChangesAsync` leaves pending changes that a later caller will try to save again. Because the failure depends on timing, it often appears only after deployment, which is why turning `ValidateScopes` off to "fix" the Development error is the worst response. ## Fixes, in order of preference | Fix | When it fits | |---|---| | Make the consumer scoped (`AddScoped<ClassScheduleCache>()`) | it holds no state worth keeping across requests | | `AddDbContextFactory<BookingDbContext>` and inject `IDbContextFactory<BookingDbContext>` | a true singleton needs fresh data now and then | | Inject `IServiceScopeFactory`, call `CreateAsyncScope()` and resolve the context inside | the work needs other scoped services too | With the factory, each refresh gets its own short-lived context that you dispose: ```csharp public class ClassScheduleCache(IDbContextFactory<BookingDbContext> factory) { public async Task<List<GymClass>> TodayAsync() { await using var db = await factory.CreateDbContextAsync(); return await db.GymClasses.AsNoTracking() .Where(c => c.StartsAt.Date == DateTime.UtcNow.Date).ToListAsync(); } } ``` `AddDbContextFactory` registers the factory as a singleton, so the singleton cache may depend on it, and it also registers `BookingDbContext` itself as scoped, so ordinary request handlers can keep injecting the context directly. ## Catching it before production Because the check runs only in Development, a team can still ship the defect if nobody starts the app locally with that registration. Two cheap guards close the gap: 1. **Integration tests.** `WebApplicationFactory<Program>` sets the environment to Development by default, so a single test that creates a client builds the container with scope validation and fails on a captive context. 2. **Validation everywhere.** `builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; })` turns the same checks on in every environment, trading a little startup time for an early failure. Either way, the first message to look for in a crash log is the "Cannot consume scoped service" text: it names both the scoped dependency and the singleton that captured it. ## Fixes that are not fixes - Disabling `ValidateScopes` hides the Development error and ships the bug. - Registering the context with `ServiceLifetime.Singleton` turns a validation error into a runtime concurrency bug. - Resolving the context through `IHttpContextAccessor` inside a singleton couples a cache to whichever request happens to be running and fails when there is none.

  • Why does the same captive dependency not fail startup when the app runs with ASPNETCORE_ENVIRONMENT=Production?
    `WebApplicationBuilder` turns on `ValidateScopes` and `ValidateOnBuild` only when the environment is Development; elsewhere it uses a default `DefaultServiceProviderFactory` without them. The scoped context is then resolved from the root provider and quietly lives as long as the app, so the bug shows up as runtime concurrency errors instead of a startup exception.
  • When would you choose IServiceScopeFactory over AddDbContextFactory for the singleton's database work?
    When the operation needs more than the context: a scoped repository, a scoped validator or another service that itself depends on the context. `CreateAsyncScope()` gives you a whole scope, so every scoped dependency inside it shares one context and is disposed together with `await using`. For plain queries, the factory is lighter and makes the context's lifetime explicit.

  • Set ValidateScopes to false, since the error only appears in Development.
  • Register the DbContext as a singleton so the singleton cache can use it.
  • A scoped context injected into a singleton is recreated for each request.
  • Production behaves like Development, so the bug cannot reach production.
  • Wrap the singleton's injected context in a using block to make it safe.