Covers diagnosing a captive dependency (scoped DbContext held by a singleton): symptoms, why Production does not catch it, confirming with ValidateScopes and tests, and fixing it by realigning lifetimes or creating scopes.
It is a captive dependency. The singleton was built once, from the first request's scope, so it holds that request's DbContext for ever. Every user now shares one context: its identity map returns stale entities that were tracked earlier, concurrent requests hit it at the same time and EF throws "A second operation was started", and the change tracker grows. Often the first scope's disposal even leaves it disposed (ObjectDisposedException).
Development would have thrown, because ValidateScopes is on only in Development by default. I confirm by enabling ValidateScopes and ValidateOnBuild and reading the exception. The fix is to make PricingService scoped, or, if it truly must be a singleton (it holds a cache), inject IDbContextFactory<AppDbContext> and create a context per operation. Then turn validation on everywhere.
"Those two symptoms together point at one shared
DbContext. A singleton is constructed once, and whatever it receives in its constructor it keeps. WhenPricingServicewas first resolved, the container gave it theAppDbContextfrom that request's scope. From then on every request, on every thread, uses that same context. EF's identity map means a product loaded at 9am is returned from the tracker at 3pm without hitting the database, so users see stale prices. And because a context only supports one operation at a time, two concurrent requests trip EF's concurrency detector and you get 'A second operation was started on this context instance'. Sometimes you also seeObjectDisposedException, because the original scope disposed the context but the singleton still holds it.For example, at [company] we [shipped a pricing change that made a service a singleton to cache tax tables]. Locally it threw immediately, but [the developer had switched the environment to Staging to test configuration], and Production has scope validation off by default, so it built fine. I confirmed by setting
ValidateScopesandValidateOnBuildto true in a local run: start-up failed with 'Cannot consume scoped service AppDbContext from singleton PricingService', which pinned it in seconds. We hot-fixed by registering the service as scoped, and moved the tax-table cache intoIMemoryCacheso it didn't need to be a singleton at all. [Errors dropped from about 3% of requests to zero.]The mistake I see is fixing the symptom by adding a lock around the context, which serialises every request and still serves stale data. The real fix is aligning lifetimes, and making the container refuse the mistake in every environment."
| Symptom | Cause |
|---|---|
| Stale data | Identity map: tracked entities are returned instead of re-reading rows |
InvalidOperationException: A second operation was started... |
EF's concurrency detector: two threads on one context |
ObjectDisposedException: Cannot access a disposed context |
The first request's scope disposed the context the singleton still holds |
Memory growth, slower SaveChanges |
Change tracker accumulates every entity ever loaded |
| Only in Production / Staging | ValidateScopes defaults to true only when IsDevelopment() |
| Step | Tool |
|---|---|
| Read the stack trace: which service called the context | Application Insights exceptions, logs |
| Re-run with validation on | UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }) |
| Check registrations of the consumer and its consumers | grep for AddSingleton<PricingService> and anything that injects it |
| Prove it in a test | Build the host in an integration test with validation on |
| Fix | When |
|---|---|
| Make the consumer scoped | It has no real reason to be a singleton (most cases) |
Inject IDbContextFactory<T> |
It must be a singleton (holds a cache or a timer) |
Inject IServiceScopeFactory, scope per operation |
It needs several scoped services together |
Move the shared state into IMemoryCache |
The only reason for singleton was caching |
After the fix, the 'second operation' exceptions in Application Insights went from [~1,200 a day] to zero, p95 latency on the pricing endpoint dropped from [480 ms] to [110 ms] because requests no longer queued behind one context, and the pod's working set stopped growing by [~150 MB a day].
Checks that the candidate recognises a captive dependency from its symptoms, knows why Production didn't catch it, and fixes the lifetime rather than the symptom.
Green flags
ValidateScopes only in Development by default, and opts in everywhereIDbContextFactory<T> / IServiceScopeFactoryRed flags
IServiceProvider inside the singletonRequest 1 scope ──► resolve PricingService (singleton, not yet built)
└─ needs AppDbContext (scoped) → take from Request 1 scope
store PricingService in ROOT singleton cache
Request 1 ends ──► scope disposes AppDbContext #1
Request 2 scope ──► resolve PricingService → root cache hit → holds AppDbContext #1
The container caches the singleton in the root; it has no idea the instance holds something owned by a dead scope.
With ValidateScopes = true, the provider wraps resolution in a CallSiteValidator:
InvalidOperationException: Cannot consume scoped service 'X' from singleton 'Y'.Cannot resolve scoped service 'X' from root provider.ValidateOnBuild builds every call site at Build(), so combined they fail at start-up instead of first resolve. Neither can see inside a factory delegate (sp => new PricingService(sp.GetRequiredService<AppDbContext>())), which is a common way the bug sneaks past validation.
HostApplicationBuilder / WebApplicationBuilder set both options to IsDevelopment(). A developer running with ASPNETCORE_ENVIRONMENT=Staging, a CI job, or Production all skip the checks. The cost of turning them on is one walk of the graph at start-up, typically milliseconds to tens of milliseconds.
DbContext tracks whether an operation is in progress; a second call on another thread throws immediately rather than corrupting the connection. It is a detector, not a guarantee: it only catches overlap at that instant, which is why the error appears at a percentage of requests that rises with load.
IOptionsSnapshot<T> (scoped).HttpClient (transient) captured in a singleton: not a validation error, but the handler is never rotated.BackgroundService constructor taking a repository.DbContext, run 50 parallel requests with bombardier or k6 and count exceptions.ValidateScopes on and read the start-up exception.The bug and the two fixes.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace Pricing;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
}
public sealed record Product(int Id, string Sku, decimal Price);
// BEFORE: singleton capturing a scoped DbContext.
public sealed class PricingServiceBroken(AppDbContext db)
{
public Task<Product?> GetAsync(int id, CancellationToken ct) =>
db.Products.FirstOrDefaultAsync(p => p.Id == id, ct); // shared across all requests
}
// FIX A: make it scoped; cache tax tables in IMemoryCache instead of a singleton field.
public sealed class PricingService(AppDbContext db, IMemoryCache cache)
{
public Task<Product?> GetAsync(int id, CancellationToken ct) =>
db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == id, ct);
}
// FIX B: it must stay a singleton (owns a timer/cache) → a context per operation.
public sealed class PricingRefresher(IDbContextFactory<AppDbContext> contexts)
{
public async Task<int> CountAsync(CancellationToken ct)
{
await using var db = await contexts.CreateDbContextAsync(ct);
return await db.Products.CountAsync(ct);
}
}
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Singleton factory (safe to inject into singletons). Since EF Core 6 this also
// registers AppDbContext as scoped for request code.
builder.Services.AddDbContextFactory<Pricing.AppDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("App")));
builder.Services.AddMemoryCache();
builder.Services.AddScoped<Pricing.PricingService>(); // was AddSingleton
builder.Services.AddSingleton<Pricing.PricingRefresher>(); // takes the singleton factory
// Catch the next one at start-up in every environment, not just Development.
builder.Host.UseDefaultServiceProvider(o =>
{
o.ValidateScopes = true;
o.ValidateOnBuild = true;
});
var app = builder.Build();
app.Run();
public partial class Program;
A guard-rail test:
using Microsoft.AspNetCore.Mvc.Testing;
namespace Pricing.Tests;
public sealed class CompositionRootTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public void Host_builds_with_scope_validation()
{
using var client = factory.WithWebHostBuilder(b => b.UseEnvironment("Production")).CreateClient();
Assert.NotNull(client); // throws during build if a captive dependency exists
}
}
lock or SemaphoreSlim. Why it is wrong: It serialises every request through one context and still returns stale tracked data. Instead: Give each unit of work its own context.AsNoTracking() everywhere and calling it fixed. Why it is wrong: Stale data improves, but the context is still shared across threads and still throws under load. Instead: Fix the lifetime.sp => new PricingService(sp.GetRequiredService<AppDbContext>())). Why it is wrong: The capture is identical, and validation can no longer see it. Instead: Change the lifetime or use IDbContextFactory<T>.IServiceProvider and resolving AppDbContext from it inside the singleton. Why it is wrong: That resolves from the root provider: one context for ever, never disposed. Instead: IServiceScopeFactory.CreateAsyncScope() per operation.PricingService may also be a singleton and now captures it. Instead: Check the consumers and let ValidateOnBuild walk the graph.This is the most common DI production bug I see, and it's almost always introduced by someone trying to optimise: "this service is expensive, make it a singleton". The lesson I take to the team is that a lifetime change is a behaviour change and needs the same review as a schema change. The cheap, permanent prevention is to make the container enforce the rule everywhere.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| Consumer becomes scoped | No real shared state | None measurable | It owns a timer or a long-lived cache |
IDbContextFactory<T> |
Singleton or background work that needs a context | You manage disposal per call | You need several scoped services in one unit of work |
IServiceScopeFactory |
Singleton needs a full scoped graph | Service-locator-ish inside one class | Simple cases where scoped consumer works |
| Lock around context | Never | Serialises traffic, still stale | Always |
I measure the fix by EF exception counts and endpoint latency percentiles in Application Insights, and I add a test that builds the host in the Production environment with validation on, so the rule is checked in CI.
ValidateOnBuild makes Build() walk every registration and try to build its call site, so a missing dependency or an unresolvable constructor fails at start-up instead of on the first request that needs it. Combined with ValidateScopes it also catches a singleton depending on a scoped service.
What it cannot catch:
sp => ...): the body is opaque code that only runs on resolution;ActivatorUtilities.CreateInstance or GetService calls in your own code.ASP.NET Core's WebApplication turns it on only in the Development environment; enable it everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateOnBuild = true; o.ValidateScopes = true; }). The start-up cost is a one-off graph walk, typically small, and it buys you a fast failure in every environment.
A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.
When the container can't build something up front, inject a factory instead of the object.
AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.Func<T> or Lazy<T>; you register them explicitly.ActivatorUtilities.CreateFactory (the generic ObjectFactory<T> overload arrived in .NET 8), which mixes your argument with container services and caches the reflection.The key rule: anything a factory creates is owned by the caller, who must dispose it. The trade-off is flexibility against hidden lifetimes: factories are the main way captive and leaked dependencies sneak in.
How to tell it (STAR)
**S:** At [company], our pricing API [served about 200 requests per second], and after a release customers started seeing stale prices while our error rate crept up to [about 3%]. **T:** I was [on call] and needed to find the cause quickly and stop it coming back. **A:** Application Insights showed every failure was EF's 'second operation' error from one service. The diff showed it had been made a singleton to cache tax tables, but it took the scoped DbContext. I ran it locally with scope validation forced on and start-up failed with the exact captive-dependency message. We hot-fixed it back to scoped, moved the cache into IMemoryCache, and I turned on ValidateScopes and ValidateOnBuild in every environment with a test that builds the host as Production. **R:** Errors went from [about 3%] to zero within [an hour], p95 latency dropped from [480 ms] to [110 ms], and the same class of bug has been caught at build time [twice] since.
Last updated 23 Nov 2026.