In ASP.NET Core 10, what goes wrong when a singleton price cache takes a scoped DbContext in its constructor, and how do you fix it?
answer
- longer lifetime holds a shorter one
- Development fails at builder.Build()
- Cannot consume scoped service from singleton
- Production: one context for every request
- IServiceScopeFactory per refresh
basics
~20 sIt is a captive dependency: the singleton keeps one DbContext for the app's lifetime. Development fails at builder.Build() with "Cannot consume scoped service"; Production starts and shares that context across concurrent requests. Create a scope per refresh with IServiceScopeFactory.
solid answer
~40 sA singleton built once holds whatever its constructor received, so a scoped `DbContext` injected into it becomes **captive**: it lives as long as the app and is shared by every request. In Development, `WebApplicationBuilder` turns on `ValidateScopes` and `ValidateOnBuild`, so `builder.Build()` throws an `AggregateException` whose inner message is "Cannot consume scoped service 'TradingDbContext' from singleton 'IQuoteCache'." In Production nothing checks, so the app starts, one context serves every request, its change tracker grows and serves stale entities, and concurrent use throws "A second operation was started on this context instance". The fix keeps the cache singleton but stops it holding the context: inject `IServiceScopeFactory`, open `await using var scope = scopes.CreateAsyncScope()` per refresh and resolve the context from `scope.ServiceProvider`.
code
csharp · 8 lines// Captive: QuoteCache is built once and keeps one TradingDbContext forever.
builder.Services.AddDbContext<TradingDbContext>(o => o.UseNpgsql(cs));
builder.Services.AddSingleton<IQuoteCache, QuoteCache>();
public class QuoteCache(TradingDbContext db) : IQuoteCache { /* ... */ }
// Development: builder.Build() throws AggregateException:
// Cannot consume scoped service 'TradingDbContext' from singleton 'IQuoteCache'.go deeper
Know the rule: a singleton must not take a scoped service such as a DbContext in its constructor, and Development reports it at startup.
Explain the two environments: the AggregateException from builder.Build() in Development, and the silent root-held context in Production, then show the IServiceScopeFactory fix.
Diagnose the production symptoms (second-operation errors, stale prices, growing memory) back to a captive dependency and choose between borrowing a scope, changing the lifetime and a singleton-safe factory.
Weigh whether shared caches belong in singletons at all versus a dedicated caching layer, and how to keep lifetime rules enforced across teams that never run in Development mode.
## The bug: a singleton that holds a scoped service A **captive dependency** is a service with a long lifetime that holds a reference to a service with a shorter lifetime. The container cannot shorten the holder's lifetime, so the shorter-lived object is kept alive as long as the holder. Picture a stock-trading dashboard. Every page shows last prices, so someone writes a singleton `QuoteCache` and gives it the app's EF Core context: ```csharp builder.Services.AddDbContext<TradingDbContext>(o => o.UseNpgsql(cs)); // scoped builder.Services.AddSingleton<IQuoteCache, QuoteCache>(); public class QuoteCache(TradingDbContext db) : IQuoteCache { public Task<List<Quote>> LatestAsync() => db.Quotes.OrderByDescending(q => q.At).Take(50).ToListAsync(); } ``` `AddDbContext` registers the context as **scoped**: one per HTTP request, disposed when the request ends. `QuoteCache` is built once, so it receives one context and keeps it forever. ## What you see in each environment | Environment | Scope validation | Result | |---|---|---| | Development | `ValidateScopes` and `ValidateOnBuild` on | `builder.Build()` throws `AggregateException` ("Some services are not able to be constructed") | | Staging, Production | off | the app starts; the bug shows up under load | In **Development** the inner exception reads: "Cannot consume scoped service 'TradingDbContext' from singleton 'IQuoteCache'." The app never starts, which is the point of turning validation on there. In **Production** the container does not check. When `QuoteCache` is first resolved, its scoped dependency is resolved against the **root** scope, so the container treats that context like a singleton too. The consequences are concrete: 1. **Shared across requests.** Every request that touches the cache uses the same `TradingDbContext`. A `DbContext` is not thread-safe, so two overlapping requests throw "A second operation was started on this context instance before a previous operation completed." 2. **Stale data.** The change tracker keeps every entity it has tracked; a later query that hits the same keys hands back the instances it already tracks instead of fresh values, so prices drift. 3. **Growing memory.** Tracked entities accumulate for the life of the process. 4. **No disposal.** The context is disposed only when the host shuts down, so everything it tracks is held far longer than intended. These failures are intermittent and load-dependent, which is why the bug survives a smoke test run outside Development, or one that sends a single request at a time. ## Variants of the same captive The constructor in the example is the obvious form; the same lifetime mismatch hides in other shapes: - **A transient in between.** The singleton takes a transient `QuoteLoader`, which takes the context. The transient is built once for the singleton, so the context is captured all the same, and scope validation still reports it because it walks the whole constructor graph. - **A factory registration.** `AddSingleton<IQuoteCache>(sp => new QuoteCache(sp.GetRequiredService<TradingDbContext>()))` hides the dependency from the build-time check; it fails only when the singleton is first resolved, and only if scope validation is on. - **Any other scoped service.** A repository, a unit of work or a service carrying the current user's data is captured just like the context, and carries one request's data into every later request. ## Fixes, in order of preference - **Keep the singleton, borrow the context per operation.** Inject `IServiceScopeFactory` (itself a singleton and explicitly allowed in singletons) and open a scope for each refresh: ```csharp public class QuoteCache(IServiceScopeFactory scopes) : IQuoteCache { private volatile IReadOnlyList<Quote> _latest = []; public async Task RefreshAsync(CancellationToken ct) { await using var scope = scopes.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService<TradingDbContext>(); _latest = await db.Quotes.AsNoTracking() .OrderByDescending(q => q.At).Take(50).ToListAsync(ct); } public IReadOnlyList<Quote> Latest => _latest; } ``` The singleton now holds only immutable data; each refresh gets a fresh context that is disposed with its scope. - **Change the cache's lifetime** to `AddScoped` if it never needed to share anything across requests. This removes the captive, but a scoped "cache" is rebuilt for every request, so it caches nothing between them. - **Give the singleton a singleton-safe dependency.** EF Core's context factory is designed for this; its registration and lifetime belong to EF Core's own topic. What does **not** fix it: injecting `IServiceProvider` and calling `GetRequiredService<TradingDbContext>()` inside the singleton. A singleton's `IServiceProvider` is the root provider, so you get the same root-held context, and with `ValidateScopes` on you get "Cannot resolve scoped service 'TradingDbContext' from root provider." instead. ## How to talk about it in an interview - Name it: a captive dependency, a lifetime mismatch where the longer-lived service wins. - Say where it is caught: at `builder.Build()` in Development, never in Production unless you turn validation on. - Describe the production symptom precisely: shared, non-thread-safe state, stale tracked entities, late disposal. - Fix the ownership, not the symptom: the singleton should create and dispose its short-lived dependencies through a scope.
- Why does the captured context fail only under load in Production?With validation off, the container resolves the scoped context against the root scope once and the singleton keeps it. A single request at a time works. Overlapping requests then use the same non-thread-safe `DbContext`, which throws "A second operation was started on this context instance", and its change tracker keeps serving stale tracked entities.
- Does a transient in between hide the captive dependency?No. If the singleton takes a transient `QuoteLoader` that itself takes the scoped context, scope validation walks the whole constructor graph and still reports "Cannot consume scoped service 'TradingDbContext' from singleton 'IQuoteCache'." In Production the transient is built once for the singleton and the context is captured just the same.
- The container hands the singleton a fresh DbContext for each request.
- Injecting IServiceProvider into the singleton and resolving the context there fixes it.
- Scope validation runs in every environment, so Production would refuse to start.
- A transient between the singleton and the context breaks the capture.
- Making the cache AddScoped fixes it with no change in behaviour.