6.4 — The Captive Dependency Problem¶
← Roadmap · Section: 6. Dependency Injection Prev: 6.3 Service lifetimes · Next: 6.5 Scopes
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A captive dependency is a short-lived service trapped inside a long-lived one — most often a scoped service injected into a singleton.
- The singleton resolves it once and holds it forever, so a per-request object becomes an application-lifetime object.
- With a
DbContextthat means a thread-safety bug and a memory leak at the same time. - The container detects it — but only in Development by default, which is exactly why it reaches production.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Captive dependency | a bug | A service held by something longer-lived than itself, so it never gets released. |
| Lifetime mismatch | the cause | Injecting a shorter lifetime into a longer one. |
| The rule | a guideline | A service may only depend on services with an equal or longer lifetime. |
ValidateScopes |
a container option | Detects lifetime mismatches at resolution time. On by default in Development only. |
InvalidOperationException |
what it throws | "Cannot consume scoped service X from singleton Y." |
IServiceScopeFactory |
an interface | The safe way for a singleton to get scoped services — create a scope per operation. |
IServiceProvider |
an interface | The container. Injecting the root one into a singleton is the common workaround, and a trap. |
| Change tracker | an EF Core component | Holds every entity a DbContext has loaded. Grows without limit if the context is never disposed. |
The concept¶
The rule in one line¶
A service may only depend on services with an equal or longer lifetime.
| Consumer | May inject | May not inject |
|---|---|---|
| Singleton | Singleton | ⚠️ Scoped, Transient* |
| Scoped | Singleton, Scoped | ⚠️ Transient* |
| Transient | Anything | — |
* Injecting a transient is legal and does not throw, but it becomes captive — see below.
Why it happens¶
From 6.3: the consumer's lifetime wins. The container resolves a constructor parameter once, when it builds the consumer. If the consumer is a singleton, that happens once for the application.
builder.Services.AddScoped<AppDbContext>(); // "one per request"
builder.Services.AddSingleton<CacheWarmer>(); // one for the app
public class CacheWarmer(AppDbContext db) // ⚠️ CAPTIVE
{
// 'db' was resolved ONCE, when CacheWarmer was created.
// It is now held for the entire application lifetime.
}
The DbContext was registered as scoped, and the registration is honoured — the container did
create it inside a scope. The problem is that the singleton kept a reference to it after that
scope ended.
A picture: a library book borrowed by someone who never returns it. The lending rules are fine. The book was meant to circulate. One person putting it on their permanent shelf breaks the system for everyone else.
How it works¶
What actually breaks¶
The abstract rule matters less than the concrete damage. With a DbContext, three things go
wrong at once.
1. It is not thread-safe. A singleton is shared by every concurrent request, so fifty
requests use one DbContext simultaneously. EF Core detects some of this and throws "A second
operation was started on this context instance before a previous operation completed" — but not
reliably, and corruption can occur silently.
2. The change tracker grows forever. A DbContext remembers every entity it has loaded so it
can detect changes. Normally it is disposed at the end of the request and that memory is
released. Held forever, it accumulates every entity the application has ever touched — a textbook
memory leak (3.5).
3. You read stale data. Because the change tracker caches entities by key, a query that returns a row already tracked gives you the cached version, not the current database state. So an update made by another request is invisible.
⚠️ All three get worse over time and under load, which is why this bug is a production problem rather than a development one.
The transient case, which does not throw¶
builder.Services.AddTransient<IReportBuilder, ReportBuilder>();
builder.Services.AddSingleton<ReportScheduler>();
public class ReportScheduler(IReportBuilder builder)
{
// No exception. Ever. But 'builder' lives for the app's lifetime.
}
ValidateScopes does not catch this, because transient into singleton is technically legal —
the container will happily create one and hand it over.
But the effect is the same: a service you declared "new every time" is now a de facto singleton. If it holds a buffer, a connection or any state, you have a leak with no warning at all.
This is the sneakier half of the problem, and worth mentioning in an interview because most people only know the scoped case.
How it actually works — detection¶
The container can catch the scoped case:
builder.Host.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = true; // catch lifetime mismatches
options.ValidateOnBuild = true; // check at startup, not first use
});
With ValidateScopes on, resolving the singleton throws:
InvalidOperationException: Cannot consume scoped service 'AppDbContext' from singleton 'CacheWarmer'.
That message is clear and names both types.
⚠️ The critical detail: both options default to on in Development and off elsewhere.
So the environment that would have caught the bug is the one you never deploy. The app starts cleanly in production and misbehaves under concurrency.
Turn both on in every environment. ValidateOnBuild costs a little startup time and moves
the failure from "the first request that happens to hit this path" to "the moment the app
starts", which is a much better place to find out.
The fixes¶
Fix 1 — inject IServiceScopeFactory and create a scope ⭐¶
The correct answer when a singleton genuinely needs a scoped service:
public class CacheWarmer(IServiceScopeFactory scopeFactory) : IHostedService
{
public async Task StartAsync(CancellationToken ct)
{
// A scope for THIS operation only
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var prices = await db.Prices.AsNoTracking().ToListAsync(ct);
// ...
} // scope disposed — DbContext released
public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}
The singleton holds the factory — which is itself a singleton, so no mismatch — and creates a short-lived scope whenever it needs scoped work. See 6.5.
Fix 2 — reconsider the lifetime¶
Often the singleton did not need to be one:
// If it has no expensive state, scoped is simpler and has no mismatch
builder.Services.AddScoped<CacheWarmer>();
⚠️ Ask why it is a singleton at all. People reach for singleton believing it is faster, but scoped service creation is very cheap. Singleton earns its place when there is genuinely shared state — a cache, a connection pool — not by default.
⚠️ Fix 3 — the one that looks right and is not¶
// ✗ WRONG — injecting the root IServiceProvider
public class CacheWarmer(IServiceProvider provider)
{
public async Task WarmAsync()
{
var db = provider.GetRequiredService<AppDbContext>(); // ⚠️ from the ROOT
}
}
This compiles, does not throw ValidateScopes, and is still broken. Resolving a scoped service
from the root provider creates it in the root scope — which lives for the whole
application. You have recreated exactly the same captive dependency, just later and less
visibly.
IServiceProvider gives you the root. IServiceScopeFactory lets you make a real scope. That
distinction is the point.
Code¶
The realistic version — a background service, which is where this comes up most:
// ✗ BROKEN — DbContext captured for the life of the application
public class OrderCleanupService(AppDbContext db) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await db.Orders.Where(o => o.IsExpired).ExecuteDeleteAsync(stoppingToken);
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
}
}
BackgroundService is registered as a singleton, so this is a captive DbContext — and it runs
for weeks.
// ✓ CORRECT — a fresh scope per iteration
public class OrderCleanupService(
IServiceScopeFactory scopeFactory,
ILogger<OrderCleanupService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope(); // INSIDE the loop
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var removed = await db.Orders
.Where(o => o.ExpiresAt < DateTimeOffset.UtcNow)
.ExecuteDeleteAsync(stoppingToken);
logger.LogInformation("Removed {Count} expired orders", removed);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break; // shutting down — normal
}
catch (Exception ex)
{
logger.LogError(ex, "Cleanup failed, will retry");
}
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
}
}
⚠️ The scope goes inside the loop, not outside. A scope created once outside gives you a
single DbContext for the service's entire life — the same bug, moved. Each iteration gets a
fresh context that is disposed when the iteration ends. See
21.2.
Interview questions¶
Q: What is a captive dependency?
It is a service held by something longer-lived than itself — most commonly a scoped service injected into a singleton. The container resolves constructor parameters once when it builds the consumer, so a singleton resolves its dependencies a single time and keeps them for the life of the application. A service registered as "one per request" becomes an application-lifetime object. The rule it violates is that a service should only depend on things with an equal or longer lifetime.
Q: What actually goes wrong with a captive DbContext?
Three things at once. It is not thread-safe, and a singleton is shared across concurrent requests, so simultaneous operations corrupt its state — sometimes surfacing as "a second operation was started on this context", sometimes silently. Its change tracker holds every entity it has ever loaded and is never disposed, so memory grows without limit. And because the tracker caches entities by key, queries return the cached version rather than current database state, so you read stale data. All three get worse under load, which is why it is a production bug rather than a development one.
Q: How do you fix it?
If the singleton genuinely needs scoped work, inject IServiceScopeFactory and create a scope
per operation — the factory is itself a singleton so there is no mismatch, and the scope is
disposed when the operation finishes. Often the better answer is to question why the consumer is
a singleton at all, since scoped service creation is very cheap and singleton should be reserved
for genuinely shared state. The fix to avoid is injecting IServiceProvider and resolving from
it, because that is the root provider — the scoped service is then created in the root scope and
you have recreated the same problem less visibly.
Q: Why does this reach production so often?
Because the detection is enabled in Development only. ValidateScopes catches the mismatch and
throws a clear exception naming both types, but it defaults to on in Development and off
everywhere else — so the environment that would have caught it is the one you never deploy. The
app starts cleanly in production and only misbehaves under concurrency. I would turn both
ValidateScopes and ValidateOnBuild on in all environments; the startup cost is small and it
moves the failure to a much better place.
Q: Can a transient be captive?
Yes, and this case is quieter because nothing throws. Injecting a transient into a singleton is
technically legal, so ValidateScopes says nothing — but the transient is still resolved once
and held for the application's lifetime. If it holds a buffer, a connection or any state, that is
a leak with no warning at all. Most people only know the scoped case, so it is worth being aware
of.
Traps ⚠️¶
ValidateScopesis Development-only by default. Turn it on everywhere.- Transient into singleton does not throw but is still captive.
- Injecting
IServiceProvidergives you the root scope, so resolving scoped services from it recreates the bug. UseIServiceScopeFactory. - Creating a scope outside a loop captures the service for the whole loop.
BackgroundServiceis a singleton, so this is the most common place it appears.- Conventional middleware is also a singleton — same problem, same fix (5.5).
IOptionsSnapshot<T>is scoped, unlikeIOptions<T>, so it cannot go in a singleton constructor (7.6).
Related¶
- 6.3 Service lifetimes — why the consumer's lifetime wins
- 6.5 Scopes —
IServiceScopeFactoryin detail - 6.13 DI traps — the other classics
- 5.5 Conventional middleware — the same trap in middleware
- 21.2 Scoped services in background services — the common real case
- 13.2 DbContext — why it must be scoped
- 3.5 Memory leaks — the leak this causes