Skip to content

6.13 — Classic DI Interview Traps

← Roadmap · Section: 6. Dependency Injection Prev: 6.12 DI and testability · Next: 7.1 Configuration system

Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

The DI mistakes interviewers actually ask about, collected. Every one of them compiles, starts, and works in development — which is precisely why they get asked.

  • Scoped into singleton — the captive dependency. The single most-asked DI question.
  • Registering DbContext as a singleton — not thread-safe, and a memory leak.
  • Resolving scoped services in Program.cs or a background service without a scope.
  • The detection that would have caught most of these is Development-only by default.

Definitions

Term What it is What it means
Captive dependency a bug A short-lived service held by a longer-lived one. See 6.4.
Root provider the app-level container app.Services. Has no request scope. Resolving scoped services from it is wrong.
ValidateScopes a container option Detects lifetime mismatches. Development-only by default.
ValidateOnBuild a container option Verifies every registration resolves, at startup. Development-only by default.
Change tracker an EF Core component Holds every entity a DbContext has loaded. Never resets if the context is never disposed.
IServiceScopeFactory an interface The correct way to create a scope from a singleton.
IOptionsSnapshot<T> an interface Scoped, unlike IOptions<T>. Cannot go in a singleton constructor.
Service locator an anti-pattern Injecting IServiceProvider to pull services out. See 6.9.

The concept

Why these bugs survive to production

Every trap in this note shares one property: it works with one user.

In development you click through the app one request at a time. A singleton DbContext is never touched concurrently. A captive dependency never has a second scope to conflict with. A memory leak never runs long enough to matter.

Then production applies concurrency and uptime, and all three surface at once.

⚠️ Worse: the container's own detection is disabled in production by default. ValidateScopes and ValidateOnBuild default to on in Development and off elsewhere — so the environment that would have caught the bug is the one you never deploy.

That is the single most useful thing to say in an interview on this topic. It explains why these are production bugs rather than development ones, and the fix is one block of code:

builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes  = true;
    options.ValidateOnBuild = true;
});

How it works

Trap 1 — Scoped into singleton ⭐ the most-asked

builder.Services.AddDbContext<AppDbContext>(...);        // scoped
builder.Services.AddSingleton<CacheWarmer>();
public class CacheWarmer(AppDbContext db) { }            // ⚠️ CAPTIVE

The singleton resolves AppDbContext once and holds it forever. Three failures at once: it is not thread-safe across concurrent requests, its change tracker grows without limit, and it returns stale cached entities.

Fix: inject IServiceScopeFactory and create a scope per operation (6.5). Full detail in 6.4.

Trap 2 — DbContext as a singleton

builder.Services.AddSingleton<AppDbContext>();           // ✗ never

Usually done "for performance", on the assumption that creating one is expensive. It is not — DbContext creation is cheap, and AddDbContextPool exists if you want pooling (13.2).

Fix: AddDbContext registers it as scoped, which is correct. Do not override that.

Trap 3 — Resolving scoped services at startup

var app = builder.Build();

var db = app.Services.GetRequiredService<AppDbContext>();   // ✗ throws
await db.Database.MigrateAsync();

InvalidOperationException: Cannot resolve scoped service from root provider.

app.Services is the root provider and there is no ambient scope during startup.

Fix:

using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();

Trap 4 — The scope outside the loop

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    using var scope = scopeFactory.CreateScope();         // ⚠️ outside
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

    while (!stoppingToken.IsCancellationRequested)
    {
        await ProcessBatchAsync(db, stoppingToken);
        await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
    }
}

This looks correct — a scope was created. But it lives for the service's entire lifetime, so the change tracker accumulates every entity from every iteration. The captive dependency, moved rather than fixed.

Fix: the scope goes inside the loop (21.2).

Trap 5 — IServiceProvider instead of IServiceScopeFactory

public class Worker(IServiceProvider provider) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        var db = provider.GetRequiredService<AppDbContext>();   // ⚠️ ROOT scope
    }
}

IServiceProvider injected into a singleton is the root provider. Resolving a scoped service from it creates it in the root scope — which lives for the whole application.

⚠️ And ValidateScopes does not catch this, because the resolution is explicit rather than a constructor mismatch. It is the quieter version of trap 1.

Fix: IServiceScopeFactory, then CreateScope().

Trap 6 — Conventional middleware constructor

public class AuditMiddleware(RequestDelegate next, AppDbContext db)   // ⚠️
{
    public async Task InvokeAsync(HttpContext context) { }
}

Conventional middleware is instantiated once, at pipeline construction — so it is a singleton (5.5).

Fix: scoped services go in the InvokeAsync parameters, which are resolved per request:

public async Task InvokeAsync(HttpContext context, AppDbContext db) { }

Trap 7 — IOptionsSnapshot<T> in a singleton

public class PriceService(IOptionsSnapshot<PriceOptions> options) { }   // ⚠️

IOptions<T> is a singleton and fine here. IOptionsSnapshot<T> is scoped, so injecting it into a singleton is a captive dependency.

Fix: use IOptions<T> if the value never changes, or IOptionsMonitor<T> — which is a singleton and still picks up changes (7.6).

Trap 8 — Duplicate registration silently overriding

builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
// ... 200 lines later, in a different extension method ...
builder.Services.AddScoped<IEmailSender, SendGridEmailSender>();

Both register. Resolving IEmailSender gives you SendGrid — last one wins — with no warning.

Fix: TryAdd in library code, so a default does not override a deliberate choice (6.6).

Trap 9 — Disposing an injected service

public async Task ProcessAsync(CancellationToken ct)
{
    using (db)                                            // ⚠️
    {
        await db.SaveChangesAsync(ct);
    }
}

You did not create it. Disposing it breaks every other service in the request sharing that scoped context (6.10).

Fix: do not. The scope disposes it.

Trap 10 — Transient disposables in a loop

foreach (var path in paths)
{
    var handle = provider.GetRequiredService<IFileHandle>();   // transient, IDisposable
    await handle.WriteAsync(path, ct);
}
// 10,000 file handles held until the scope ends

Transient disposables are tracked by the scope and disposed when it ends — not when you finish with them.

Fix: a scope per iteration, or do not register disposables as transient.


The quick reference 🎯

Trap Symptom Fix
Scoped → singleton Corruption under load, growing memory IServiceScopeFactory
Singleton DbContext "A second operation was started..." Keep it scoped
Scoped at startup "Cannot resolve scoped service from root provider" CreateScope()
Scope outside the loop Memory grows over hours Scope inside the loop
IServiceProvider in a singleton Silent captive dependency IServiceScopeFactory
Scoped in middleware constructor Captive DbContext Move to InvokeAsync params
IOptionsSnapshot in a singleton Captive dependency IOptions or IOptionsMonitor
Duplicate registration Wrong implementation, silently TryAdd
Disposing an injected service ObjectDisposedException mid-request Do not dispose it
Transient disposables in a loop Handle exhaustion Scope per iteration

Code

The defensive configuration that catches most of these at startup:

var builder = WebApplication.CreateBuilder(args);

// Turn the Development-only safety net on EVERYWHERE
builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes  = true;      // catches traps 1, 6, 7
    options.ValidateOnBuild = true;      // catches missing registrations at startup
});

⚠️ ValidateOnBuild adds startup time proportional to the number of registrations — a few hundred milliseconds on a large application. That is a good trade for turning a first-request failure in production into a startup failure in CI.

And the background service pattern that avoids traps 3, 4, 5 and 10 together:

public class OrderCleanupService(
    IServiceScopeFactory scopeFactory,                   // ✓ not IServiceProvider
    ILogger<OrderCleanupService> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await using var scope = scopeFactory.CreateAsyncScope();   // ✓ 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;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Cleanup failed, will retry");
            }

            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
}

Four things right in that one method: the scope factory rather than the provider, the scope inside the loop, CreateAsyncScope because DbContext is IAsyncDisposable, and cancellation treated as normal shutdown rather than an error.


Interview questions

Q: What is the most common DI mistake you see?

Injecting a scoped service into a singleton — the captive dependency. The singleton resolves it once at construction and holds it for the application's lifetime, so a DbContext meant to live one request ends up shared across every concurrent request. That is a thread-safety bug, a memory leak because the change tracker never resets, and a correctness bug because you read stale cached entities. The reason it reaches production is that the container's scope validation is enabled in Development only by default, so the environment that would catch it is the one you never deploy.

Q: Why does a background service need special handling for DbContext?

Because BackgroundService is registered as a singleton and there is no ambient scope outside an HTTP request, so injecting a scoped service into it is a captive dependency, and resolving one from app.Services throws. You inject IServiceScopeFactory and create a scope per unit of work. The subtle part is that the scope has to go inside the work loop — creating it once outside looks correct and gives you a single DbContext for the service's entire lifetime, which is the same bug relocated rather than fixed.

Q: Why is injecting IServiceProvider into a singleton not a fix for that?

Because the provider you receive is the root one, so resolving a scoped service from it creates that service in the root scope, which lives for the whole application. You have recreated the captive dependency less visibly — and scope validation will not catch it, because the resolution is an explicit call rather than a constructor mismatch the container can inspect. IServiceScopeFactory is the right dependency, because it gives you a genuine short-lived scope.

Q: How would you make these bugs surface earlier?

Enable ValidateScopes and ValidateOnBuild in every environment rather than accepting the Development-only default. Scope validation turns a captive dependency into a startup exception naming both types, and build validation walks every registration and confirms it can actually be resolved, so a missing dependency fails at startup instead of on the first request that reaches that path. It costs some startup time on a large application, which is a good trade for finding the problem in CI rather than production.


Traps ⚠️

  • ValidateScopes and ValidateOnBuild are Development-only by default. Enable them everywhere.
  • Transient into singleton does not throw but is still captive.
  • IServiceProvider in a singleton gives the root scope, and validation misses it.
  • A scope created outside a loop is a captive dependency in disguise.
  • IOptionsSnapshot<T> is scoped, unlike IOptions<T>.
  • Conventional middleware is a singleton — scoped services go in InvokeAsync.
  • Duplicate registrations silently override, last one wins.
  • Never dispose an injected service.
  • All of these work fine with one user, which is why they reach production.


Sources