Captive dependencies (a singleton holding a scoped or transient service), the data-leak and thread-safety symptoms, ValidateScopes and ValidateOnBuild, and fixes with IServiceScopeFactory, lifetime changes and IHttpClientFactory.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
"A captive dependency happens when a service is held by something that lives longer than it does. The classic case is a singleton that takes a scoped
DbContextor anICurrentUserin its constructor. The singleton is built once, so it captures the first scope's instance and every later request shares it. You see two kinds of symptoms. One is wrong data: user A's tenant or tracked entities show up for user B. The other is concurrency errors: EF Core throws 'A second operation was started on this context instance', or you getObjectDisposedExceptiononce the original scope is disposed.To diagnose it, I first turn on
ValidateScopesandValidateOnBuildin every environment where tests run.ValidateOnBuildwalks every registration when the container is built and fails startup with 'Cannot consume scoped service X from singleton Y'. The host only enables them in Development by default, which is why the bug can reach staging. If validation can't see it, for example because the service is resolved by hand fromIServiceProvideror a transient is captured, I take a memory dump or put a breakpoint in the scoped service's constructor and count how often it runs. In a dump,dumpheap -statshows oneAppDbContextalive for hours. For example, at [company] we had a singletonINotificationServicethat captured a scopedITenantContext, and [N] emails went out with the wrong tenant's branding before we caught it. I made the service scoped, addedValidateOnBuildto the integration test host, and added a test that resolves the root provider with validation on. [Result: zero recurrences, and CI caught two more captives in the next quarter.]The fix depends on the consumer. If it doesn't need to be a singleton, make it scoped. If it must be, like a
BackgroundServiceor a cache, injectIServiceScopeFactoryand create a scope per unit of work, such as each message or each timer tick. The mistake I see is fixing it by making theDbContexta singleton too. Lifetimes only go one way: a service can depend on things that live as long or longer, never shorter."
| Consumer → depends on | Singleton | Scoped | Transient |
|---|---|---|---|
| Singleton | OK | Captive (validation catches it) | Captive (validation does not catch it) |
| Scoped | OK | OK | OK (lives for the scope) |
| Transient | OK | OK (if resolved in a scope) | OK |
| Symptom | Likely captive |
|---|---|
| Another user's or tenant's data in a response | ICurrentUser/ITenantContext in a singleton |
InvalidOperationException: A second operation was started on this context instance |
DbContext shared across concurrent requests |
| Stale data that never refreshes | Change tracker of a long-lived DbContext |
ObjectDisposedException after the first request |
Scoped service disposed with its scope, still referenced |
| HTTP calls hit an old IP after a DNS change | Typed HttpClient (transient) captured by a singleton |
| Memory growing steadily | Long-lived DbContext tracking every entity it ever loaded |
| Option | Checks | When it runs | Default |
|---|---|---|---|
ValidateScopes |
Scoped resolved from root/singleton | At resolution | true in Development |
ValidateOnBuild |
Every registration can be built, including scope rules | At Build() |
true in Development |
A multi-tenant SaaS API had a singleton ReportCache that took ITenantContext (scoped) in its constructor. It worked locally with one tenant. In production it cached the first tenant's ID, and about 0.4% of report requests over two days returned another tenant's figures, which made it a Privacy Act notifiable-breach assessment. Making the cache take the tenant ID as a key, and enabling ValidateOnBuild in the CI test host, closed it. The validation found three similar registrations elsewhere.
Checks that the candidate understands DI lifetimes deeply enough to diagnose a real production bug, including the security impact.
Green flags
ValidateScopes/ValidateOnBuild and that they are on only in Development.IServiceScopeFactory correctly in a BackgroundService.HttpClient).Red flags
DbContext a singleton to fix it.Root ServiceProvider (lives for the app)
├── singleton cache: ReportCache ──holds──▶ TenantContext #1 ← captive!
│
├── Scope A (request 1): TenantContext #1, AppDbContext #1 (disposed at end of request)
├── Scope B (request 2): TenantContext #2, AppDbContext #2
└── Scope C (request 3): TenantContext #3, AppDbContext #3
A singleton is resolved once, and its constructor arguments are resolved at that moment, from whatever scope triggered it, or from the root. It keeps those references forever.
DbContext breaks firstDbContext is not thread-safe. EF Core detects concurrent use and throws InvalidOperationException ("A second operation was started on this context instance before a previous operation completed"). It also keeps a change tracker: every entity it loads stays referenced, so a long-lived context leaks memory and returns stale tracked instances instead of fresh rows.
ValidateScopes: the provider tracks whether a resolution is happening inside a scope. Resolving a scoped service from the root provider throws InvalidOperationException: Cannot resolve scoped service 'X' from root provider. Building a singleton whose dependency graph contains a scoped service throws Cannot consume scoped service 'X' from singleton 'Y'.ValidateOnBuild: at BuildServiceProvider() it tries to build a call-site for every descriptor, reporting missing registrations and scope violations as an AggregateException. Open generics and factories that resolve services dynamically are only partly checked.The generic host turns both on when IHostEnvironment.IsDevelopment(). Turn them on explicitly:
builder.Host.UseDefaultServiceProvider(o =>
{
o.ValidateScopes = true;
o.ValidateOnBuild = true;
});
The cost is a slower startup (milliseconds to a few hundred milliseconds in large apps), which is why some teams enable it only in Development and test hosts.
| Case | Why it is missed |
|---|---|
| Transient captured by singleton | Transients are allowed anywhere; the container doesn't know you meant "short-lived" |
sp.GetRequiredService<T>() inside a singleton method |
Dynamic resolution from the root; caught only at runtime with ValidateScopes |
| Static fields holding a resolved service | Outside the container entirely |
| Closures in a singleton capturing a scoped object | Normal object references |
Typed HttpClients are the common transient case. IHttpClientFactory rotates the underlying HttpMessageHandler every 2 minutes by default (HandlerLifetime) to pick up DNS changes. A singleton holding a typed client keeps one handler forever.
| Situation | Fix |
|---|---|
| Service doesn't need to be singleton | Make it scoped |
BackgroundService / hosted service |
Inject IServiceScopeFactory; await using var scope = factory.CreateAsyncScope(); per message or tick |
| Singleton needs per-request data | Pass it as a method parameter, or read IHttpContextAccessor.HttpContext per call |
| Singleton needs HTTP | Inject IHttpClientFactory and call CreateClient per use, or use a single HttpClient with SocketsHttpHandler.PooledConnectionLifetime |
Singleton needs a DbContext |
IDbContextFactory<T> (AddDbContextFactory or AddPooledDbContextFactory), create and dispose per operation |
dotnet-dump collect, then dumpheap -stat and gcroot <address> on the DbContext: the root chain goes through the singleton.GetHashCode() of the injected service per request: identical values across requests mean capture.AddSingleton<ReportCache>() that takes a scoped ITenantContext. Run in Production environment (no error), then Development (startup fails). Read the message.ServiceCollection with ValidateOnBuild = true and asserts no exception.HttpClient in a singleton, change the hosts file, and observe the old IP is still used after 2 minutes.BackgroundService to use CreateAsyncScope per iteration and check with a constructor counter.Before: a singleton capturing scoped services. After: scoped by default, and a scope per unit of work where a singleton is unavoidable.
// BEFORE: captive dependencies
namespace Reports;
public sealed class ReportCache(ITenantContext tenant, AppDbContext db) // both scoped!
{
public Task<Report?> GetAsync(int id, CancellationToken ct) =>
db.Reports.FirstOrDefaultAsync(r => r.Id == id && r.TenantId == tenant.TenantId, ct); // tenant #1 forever
}
// builder.Services.AddSingleton<ReportCache>();
// AFTER (1): make the consumer scoped; per-request data stays per request
namespace Reports;
public sealed class ReportReader(ITenantContext tenant, AppDbContext db)
{
public Task<Report?> GetAsync(int id, CancellationToken ct) =>
db.Reports.AsNoTracking()
.FirstOrDefaultAsync(r => r.Id == id && r.TenantId == tenant.TenantId, ct);
}
// AFTER (2): a background worker must be a singleton, so it creates a scope per message
public sealed class ReportWorker(IServiceScopeFactory scopes, ILogger<ReportWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await using AsyncServiceScope scope = scopes.CreateAsyncScope(); // fresh DbContext each time
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
int pending = await db.Reports.CountAsync(r => !r.Generated, stoppingToken);
logger.LogInformation("{Pending} reports pending", pending);
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}
// Program.cs: validate in every environment that runs tests
builder.Host.UseDefaultServiceProvider(o =>
{
o.ValidateScopes = true;
o.ValidateOnBuild = true;
});
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Main")));
builder.Services.AddScoped<ITenantContext, HttpTenantContext>();
builder.Services.AddScoped<ReportReader>();
builder.Services.AddHostedService<ReportWorker>();
DbContext as a singleton. Why it is wrong: DbContext isn't thread-safe and its change tracker grows forever; you swap a startup error for runtime corruption. Instead: Make the consumer scoped or use IDbContextFactory<T>.ValidateScopes because it "breaks startup". Why it is wrong: The validator found a real bug; disabling it hides it until production. Instead: Fix the lifetime and keep validation on in Development and test hosts.app.Services.GetRequiredService<ScopedThing>() at startup or in a singleton. Why it is wrong: It resolves from the root provider, so the scoped instance lives forever. Instead: using var scope = app.Services.CreateScope(); and resolve from it.BackgroundService constructor and reusing it for every iteration. Why it is wrong: It is still a captive; the DbContext lives for the life of the worker. Instead: Create and dispose a scope per message or per tick.HttpClient or a transient with per-operation state is allowed by the container. Instead: Review singleton constructors by hand; inject IHttpClientFactory or factories.IHttpContextAccessor, or pass the value as a parameter.IDisposable services (connections, contexts) leak until GC finalisation, if ever. Instead: await using var scope = scopeFactory.CreateAsyncScope();.Captive dependencies are the most common DI bug I see in production, and they are a security issue as much as a correctness one, because multi-tenant data leaks are notifiable under the Privacy Act. I treat lifetime validation as a non-negotiable CI check. I also review every singleton constructor: anything with per-request meaning there is a finding.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Make consumer scoped | Request-handling services | A new instance per request (cheap) | Background workers, caches shared across requests |
IServiceScopeFactory per unit of work |
Hosted services, message consumers | A bit of plumbing; must dispose | Inside normal request code (you already have a scope) |
IDbContextFactory<T> |
Singletons or Blazor Server needing short-lived contexts | You manage disposal | Normal scoped request code |
| Pass data as parameters | Singleton algorithms needing tenant/user | Signature changes | Deep call chains where a scoped service is cleaner |
To measure the fix, I count constructor invocations of the scoped service per request in a test, and watch the DbContext instance count in a memory dump (it should be roughly the number of in-flight requests, not 1).
DIP says high-level policy should not depend on low-level details; both should depend on abstractions, and the abstraction belongs to the high-level side. For example, the domain or application layer defines IPaymentGateway, and the infrastructure project implements it with Stripe; the arrow of source dependency points inwards. Dependency injection is a technique for supplying those implementations (constructor injection), and the .NET DI container is a tool that automates it. You can use a container without inverting anything (if interfaces live next to their implementations in infrastructure), and you can invert dependencies without a container.
Two different limits produce similar errors:
EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.EADDRNOTAVAIL, "Cannot assign requested address"): too many outbound connections to the same destination, usually closed sockets stuck in TIME_WAIT for 60 s.The classic .NET cause is new HttpClient() per request. Fix it with a shared HttpClient using SocketsHttpHandler { PooledConnectionLifetime = ... }, or IHttpClientFactory. Diagnose with ls /proc/<pid>/fd | wc -l, lsof -p, ss -s and ss -tan state time-wait.
How to tell it (STAR)
**S:** At [company] we ran a multi-tenant reporting API for [~200] tenants, and a support ticket said one customer could see another's figures. **T:** I was on call and had to stop the leak, find the cause and make sure it couldn't recur. **A:** Telemetry showed mismatched tenant IDs on about [0.4%] of report calls since a release that added a singleton cache. A breakpoint showed the tenant context was built once, and running in Development reproduced the 'Cannot consume scoped service from singleton' error that validation had been hiding outside Development. I switched the cache off with a feature flag within [20 minutes], then made the cache key tenant-aware, removed the scoped dependency, and helped with the breach assessment. **R:** The leak stopped immediately. Enabling `ValidateOnBuild` in CI caught [three] similar registrations before release, and we had [zero] recurrences.
Last updated 18 Nov 2026.