📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your ASP.NET Core API sometimes returns another user's data, and after a refactor startup fails with "Cannot consume scoped service 'AppDbContext' from singleton". What is a captive dependency, how do you diagnose and fix it, and how do ValidateScopes and ValidateOnBuild help?

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.

Mid-Level Debugging Intermediate captive-dependency debugging dependency-injection design-patterns ef-core singleton

🎯 Key points

  • A captive dependency is a service held by a consumer with a longer lifetime: scoped or transient inside a singleton lives for the whole process
  • Symptoms: user or tenant data leaking between requests, 'A second operation was started on this context instance', stale data, ObjectDisposedException, stale DNS in HttpClient
  • ValidateScopes throws 'Cannot consume scoped service from singleton' and 'Cannot resolve scoped service from root provider' at resolution
  • ValidateOnBuild checks every registration when the provider is built; both are on by default only in the Development environment
  • Enable both in every environment's test run (UseDefaultServiceProvider) so CI catches it, not production
  • Fix by making the consumer scoped, or injecting IServiceScopeFactory and creating a scope per unit of work (BackgroundService, singleton handlers)
  • Transient-in-singleton is also captive and not caught by validation: typed HttpClient captured by a singleton keeps one handler forever
  • Never store per-request state (current user, tenant) in singleton fields; read it per call via IHttpContextAccessor or pass it as a parameter

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 DbContext or an ICurrentUser in 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 get ObjectDisposedException once the original scope is disposed.

To diagnose it, I first turn on ValidateScopes and ValidateOnBuild in every environment where tests run. ValidateOnBuild walks 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 from IServiceProvider or 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 -stat shows one AppDbContext alive for hours. For example, at [company] we had a singleton INotificationService that captured a scoped ITenantContext, and [N] emails went out with the wrong tenant's branding before we caught it. I made the service scoped, added ValidateOnBuild to 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 BackgroundService or a cache, inject IServiceScopeFactory and create a scope per unit of work, such as each message or each timer tick. The mistake I see is fixing it by making the DbContext a singleton too. Lifetimes only go one way: a service can depend on things that live as long or longer, never shorter."


The lifetime rule

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

Symptoms and what they mean

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

Validation options

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands DI lifetimes deeply enough to diagnose a real production bug, including the security impact.

Green flags

  • Names "captive dependency" and states the lifetime rule.
  • Connects cross-user data and EF Core concurrency errors to the cause.
  • Knows ValidateScopes/ValidateOnBuild and that they are on only in Development.
  • Uses IServiceScopeFactory correctly in a BackgroundService.
  • Mentions the transient-in-singleton blind spot (typed HttpClient).

Red flags

  • Makes DbContext a singleton to fix it.
  • Disables validation.
  • Doesn't see a cross-tenant leak as a serious incident.

📚 Learn in depth

1. How lifetimes are stored

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.

2. Why DbContext breaks first

DbContext 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.

3. What the validators do

  • 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.

4. Captives validation cannot see

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.

5. Fix patterns

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

6. Diagnosing without validation

  • Breakpoint or a counter in the scoped service's constructor: it should run once per request.
  • dotnet-dump collect, then dumpheap -stat and gcroot <address> on the DbContext: the root chain goes through the singleton.
  • Log GetHashCode() of the injected service per request: identical values across requests mean capture.

Try it yourself

  1. Register AddSingleton<ReportCache>() that takes a scoped ITenantContext. Run in Production environment (no error), then Development (startup fails). Read the message.
  2. Write an xUnit test that builds the app's ServiceCollection with ValidateOnBuild = true and asserts no exception.
  3. Capture a typed HttpClient in a singleton, change the hosts file, and observe the old IP is still used after 2 minutes.
  4. Rewrite a BackgroundService to use CreateAsyncScope per iteration and check with a constructor counter.

💻 Code

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>();

⚠ Common mistakes

  • Mistake: "Fixing" the error by registering 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>.
  • Mistake: Turning off 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.
  • Mistake: Calling 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.
  • Mistake: Creating one scope in a 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.
  • Mistake: Assuming validation catches transients. Why it is wrong: A singleton holding a typed HttpClient or a transient with per-operation state is allowed by the container. Instead: Review singleton constructors by hand; inject IHttpClientFactory or factories.
  • Mistake: Storing the current user or tenant in a singleton field set by middleware. Why it is wrong: Concurrent requests overwrite each other; this is a data breach waiting to happen. Instead: Use a scoped service, IHttpContextAccessor, or pass the value as a parameter.
  • Mistake: Forgetting to dispose the scope you created. Why it is wrong: Scoped IDisposable services (connections, contexts) leak until GC finalisation, if ever. Instead: await using var scope = scopeFactory.CreateAsyncScope();.

🏛 Senior insight: trade-offs

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).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about constructor injection and lifetimes Why: Checks the difference between the DI principle and the container mechanics
    How to answer

    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.

  2. When: Candidate mentions a typed HttpClient captured by a singleton Why: Checks HttpClient lifetime, handler rotation and socket exhaustion
    How to answer

    Two different limits produce similar errors:

    1. Descriptor exhaustion (EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.
    2. Ephemeral port exhaustion (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.

🛠 Real-world problems: how you handle them

Singleton cache captured the first tenant and leaked reports across tenants
Situation
A multi-tenant reporting API on .NET [10] in Azure Australia East, serving [~200] tenants and [~3 million] requests a day. A singleton `ReportCache` was added in a refactor and took a scoped `ITenantContext` in its constructor.
Signals
A customer support ticket: a tenant saw another organisation's figures. Application Insights showed responses whose tenant ID didn't match the caller's claim on [~0.4%] of report requests, starting with the release on [date].
Investigation
Reproduced locally with two tenants in parallel requests. A breakpoint in `HttpTenantContext`'s constructor fired once, not per request. Running the app with `ASPNETCORE_ENVIRONMENT=Development` failed at startup with 'Cannot consume scoped service ITenantContext from singleton ReportCache'. Staging and Production ran without validation, which is why it shipped.
Resolution
Immediate: disabled the cache with a feature flag (all requests hit the database, p95 rose from [80 ms] to [140 ms]). Real fix: made the cache key include the tenant ID, passed the tenant as a parameter, and removed the scoped dependency. Ran a data-exposure assessment for the Notifiable Data Breaches scheme.
Prevention
Enabled `ValidateScopes` and `ValidateOnBuild` in the integration-test host and Staging; added a test that builds the provider with validation; added a review checklist item: 'no per-request services in singleton constructors'; added a response-level assertion in telemetry comparing response tenant to caller tenant.

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.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me