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

📚 Interview question

After a release, your API starts returning stale data for some users, and under load the logs show "A second operation was started on this context instance before a previous operation completed". You find a singleton PricingService that takes the scoped AppDbContext in its constructor. Explain what is happening, how you would confirm it, and how you fix it properly.

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.

Mid-Level Debugging Intermediate captive-dependency dbcontext dependency-injection ef-core service-lifetimes validate-scopes

🎯 Key points

  • Captive dependency: the singleton holds the first scope's DbContext for the process lifetime
  • Symptoms: stale tracked entities (identity map), concurrent-use InvalidOperationException, growing change tracker, ObjectDisposedException once the first scope ends
  • The host builder sets ValidateScopes and ValidateOnBuild to IsDevelopment(), so other environments build the graph silently unless you opt in
  • Confirm: run with ValidateScopes = true / ValidateOnBuild = true, read the 'Cannot consume scoped service from singleton' exception, check the stack trace
  • Fix 1: make the consumer scoped (and check everything that takes it)
  • Fix 2: if it must be a singleton, inject a singleton IDbContextFactory<T> or IServiceScopeFactory and create per operation
  • Prevent: enable both validations in every environment, a host-build test, and review lifetime changes like behaviour changes

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Those two symptoms together point at one shared DbContext. A singleton is constructed once, and whatever it receives in its constructor it keeps. When PricingService was first resolved, the container gave it the AppDbContext from 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 see ObjectDisposedException, 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 ValidateScopes and ValidateOnBuild to 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 into IMemoryCache so 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."


Why each symptom appears

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

Diagnosis steps

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 options

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

Production example

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

🔍 What the interviewer is checking

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

  • Names captive dependency and explains the identity map and concurrency detector
  • Knows the host enables ValidateScopes only in Development by default, and opts in everywhere
  • Offers scoped consumer or IDbContextFactory<T> / IServiceScopeFactory
  • Adds prevention: validation everywhere, a host-build test, lifetime changes reviewed like behaviour changes
  • Generalises: checks the consumers of the fixed service and other singletons for the same pattern

Red flags

  • Proposes a lock around the context
  • Resolves the context from IServiceProvider inside the singleton
  • Can't explain why it only fails under load

📚 Learn in depth

1. How the capture happens

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

2. What ValidateScopes actually checks

With ValidateScopes = true, the provider wraps resolution in a CallSiteValidator:

  • Resolving a singleton whose call-site graph contains a scoped service throws InvalidOperationException: Cannot consume scoped service 'X' from singleton 'Y'.
  • Resolving a scoped service from the root provider throws 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.

3. Why Development and Production differ

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.

4. EF Core's concurrency detector

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.

5. Variations of the same bug

  • A singleton that takes IOptionsSnapshot<T> (scoped).
  • Middleware (a singleton by convention) that takes a scoped service in its constructor.
  • A typed HttpClient (transient) captured in a singleton: not a validation error, but the handler is never rotated.
  • A BackgroundService constructor taking a repository.

Try it yourself

  1. Reproduce: singleton holding a scoped DbContext, run 50 parallel requests with bombardier or k6 and count exceptions.
  2. Turn ValidateScopes on and read the start-up exception.
  3. Register the singleton with a factory delegate and see validation miss it.
  4. Write an xUnit test that builds the real host with both validations on and asserts it starts.

💻 Code

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
    }
}

⚠ Common mistakes

  • Mistake: Wrapping the shared context in a 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.
  • Mistake: Adding 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.
  • Mistake: Switching the singleton to a factory delegate (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>.
  • Mistake: Injecting 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.
  • Mistake: Only fixing the one service. Why it is wrong: Everything that injects PricingService may also be a singleton and now captures it. Instead: Check the consumers and let ValidateOnBuild walk the graph.
  • Mistake: Leaving scope validation at the default. Why it is wrong: It is off outside Development, which is exactly where this bug ships. Instead: Enable it in every environment and add a host-build test.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions turning on ValidateOnBuild Why: Checks they know the limits of build-time validation (factory delegates, open generics)
    How to answer

    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:

    • anything inside a factory delegate (sp => ...): the body is opaque code that only runs on resolution;
    • open generics, which can't be checked until a closed type is requested;
    • types created later with 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.

  2. When: Candidate mentions DbContext not being thread-safe Why: Checks understanding of DbContext concurrency and parallel patterns
    How to answer

    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.

  3. When: Candidate suggests injecting a factory instead Why: Checks factory injection trade-offs
    How to answer

    When the container can't build something up front, inject a factory instead of the object.

    • A factory registration (AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.
    • Unlike Autofac, the built-in container (still true in .NET 10) does not auto-supply Func<T> or Lazy<T>; you register them explicitly.
    • For run-time values, define a small typed factory interface and implement it with 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.

🛠 Real-world problems: how you handle them

Singleton pricing service captured a scoped DbContext after a 'performance' change
Situation
[Retail pricing API, about 200 requests per second at peak, Azure App Service in Australia East]. A release changed PricingService from scoped to singleton to cache GST and discount tables between requests.
Signals
Application Insights showed a spike in InvalidOperationException 'A second operation was started on this context instance' at [~3%] of pricing requests, plus occasional ObjectDisposedException. Customers reported prices that did not change after a promotion went live. Working set grew [~150 MB a day].
Investigation
Grouped exceptions by operation and stack trace: all came from PricingService.GetAsync. Diffed the release and found AddScoped changed to AddSingleton. Ran the API locally with ASPNETCORE_ENVIRONMENT=Production and UseDefaultServiceProvider(ValidateScopes = true, ValidateOnBuild = true): start-up failed with 'Cannot consume scoped service AppDbContext from singleton PricingService'. Took a dotnet-gcdump from one instance and saw a single AppDbContext holding [hundreds of thousands of] tracked Product entities.
Resolution
Immediate: hot-fix release reverting PricingService to scoped and restarting instances. Real fix: moved the GST and discount tables into IMemoryCache with a 10-minute absolute expiry, so nothing needed to be a singleton; a separate singleton refresher uses IDbContextFactory<AppDbContext> per refresh.
Prevention
Enabled ValidateScopes and ValidateOnBuild in every environment. Added an integration test that builds the host in the Production environment. Added a pull-request checklist item: any lifetime change needs a reviewer to check the dependency graph. Alert on EF concurrency exceptions above zero.

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.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me