Volume 2 · Chapter 4 — ASP.NET Core Enterprise Development

Dependency Injection Internals

Goutham Mayaluri 9 min read .NETC#ASP.NET CoreDependency Injection

4.1 Introduction

Dependency Injection is built into ASP.NET Core and is used by almost every subsystem - logging, configuration, authentication, EF Core, and your own services. DI lets classes receive their collaborators from a container instead of constructing them, which decouples components, makes them testable, and centralizes wiring. Volume 6 covers DI architecture in depth; this chapter focuses on how the ASP.NET Core container works and the lifetime rules that cause the most production bugs.

4.2 The Point: Depend on Abstractions

Without DI, a class constructs its own dependencies, hard-coding the implementation and making it untestable. With DI, the class declares a dependency on an interface and the container supplies it - so the implementation can be swapped (a test double, a different provider) without changing the consumer.


// Tight coupling - can't test or swap the implementation.
public class OrderService { private readonly SqlRepository _repo = new(); }

// DI - depends on an abstraction, supplied by the container.
public class OrderService
{
    private readonly IRepository _repo;
    public OrderService(IRepository repo) => _repo = repo;   // constructor injection
}

4.3 The Container: ServiceCollection and ServiceProvider

At startup you register services in theIServiceCollection(mapping service types to implementations and lifetimes). Building the app produces theServiceProvider- the runtime container that resolves services and constructs object graphs, recursively supplying each constructor’s dependencies.


builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
builder.Services.AddTransient<IEmailService, SmtpEmailService>();
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); // open generic

4.4 Service Lifetimes

Lifetime Instances Typical use
Transient New every time it is requested Lightweight, stateless helpers
Scoped One per request scope DbContext, unit of work, per-request state
Singleton One for the whole application Stateless services, caches, configuration

ASP.NET Core creates a DI scope per HTTP request automatically, so scoped services live for one request and are disposed when it ends - which is exactly whyDbContextis scoped (one unit of work per request).

4.5 The Captive Dependency Trap

The most common DI bug is injecting a shorter-lived (scoped) service into a longer-lived (singleton) one. The singleton captures the scoped instance and holds it for the application’s lifetime, so a per-requestDbContextis shared across all requests - causing threading errors and stale data.

sequenceDiagram
  autonumber
  participant Root as Singleton Cache
  participant Ctx as Scoped DbContext
  participant R1 as Request 1
  participant R2 as Request 2
  Root->>Ctx: injected & captured (BUG)
  R1->>Root: use
  Root->>Ctx: query (scope of R1)
  R2->>Root: use
  Root->>Ctx: SAME captured context (wrong scope!)
  Note over Root,Ctx: Scoped instance is now effectively a singleton

The fix is to injectIServiceScopeFactoryinto the singleton and create a fresh scope per unit of work, and to enableValidateScopesso the container catches the mistake at startup.


public sealed class BackgroundProcessor(IServiceScopeFactory scopeFactory) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            using var scope = scopeFactory.CreateScope();   // fresh scope per unit of work
            var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            await ProcessBatchAsync(db, ct);
        }
    }
}
Senior Interview Question

What is the difference between Transient, Scoped, and Singleton?

They control how long a service instance lives and how it’s shared. A Transient service is created anew every time it is requested, so each consumer (and each injection) gets its own instance - suited to lightweight, stateless helpers where sharing doesn’t matter. A Scoped service is created once per scope and shared within that scope; in ASP.NET Core a scope corresponds to an HTTP request, so a scoped service lives for the duration of one request and is disposed when the request ends - which is whyDbContextis scoped, since you want one unit of work per request andDbContextis not thread-safe or meant to be shared across requests. A Singleton is created once and shared for the entire application lifetime, so every consumer gets the same instance - suited to stateless services, caches, configuration, and clocks, but it must be thread-safe because many concurrent requests use it simultaneously. The critical subtlety is composition: a service can only safely depend on services with an equal-or-longer lifetime, so a singleton must not depend on a scoped (or transient with per-request state) service - that’s the captive-dependency bug. So I choose lifetimes based on state and sharing needs: transient for cheap stateless helpers, scoped for per-request state like DbContext and units of work, and singleton for shared stateless resources - and I’m careful about how lifetimes nest.

Senior Interview Question

Why should a singleton not depend on a scoped service, and how do you handle it when you must?

Because the singleton lives for the whole application while the scoped service is meant to live for only one request, so when a singleton takes a scoped dependency in its constructor, it captures that single scoped instance and holds onto it forever - a “captive dependency.” The scoped service (say aDbContext) then effectively becomes a singleton, used across all requests and threads, which is wrong and dangerous:DbContextis not thread-safe so concurrent requests corrupt its state and throw, its change tracker accumulates stale data, and per-request state leaks between requests. It’s insidious because the code compiles and often works under light load, only failing under concurrency. When a singleton (or a hosted/background service, which is effectively singleton) genuinely needs a scoped service, the correct approach is not to inject it directly but to injectIServiceScopeFactoryand create a fresh scope for each unit of work: callCreateScope(), resolve the scoped service from that scope’s provider, do the work, and dispose the scope - which mirrors how the framework creates a scope per HTTP request. This gives each unit of work its own correctly-scoped, disposed instance. I also enable scope validation (ValidateScopes/ValidateOnBuild, on by default in development) so the container detects captive dependencies at startup and throws, catching the mistake immediately rather than in production under load. So the rule is: a service may only depend on services of equal-or-longer lifetime; when a long-lived service needs a short-lived one, create a scope per operation via the scope factory rather than capturing it.

Senior Interview Question

Why is constructor injection preferred, and what is wrong with the service locator pattern?

Constructor injection is preferred because it makes a class’s dependencies explicit and enforced: the constructor signature declares exactly what the class needs, the object cannot be created without those dependencies, and the dependencies are typicallyreadonlyand available for the object’s whole life. This makes the class honest (you can see its collaborators at a glance), testable (you construct it in a test by passing test doubles, no container needed), and safe (missing dependencies fail at construction, and often at startup with scope/graph validation). The service locator pattern - injecting theIServiceProviderand callingGetService<T>()inside methods to pull dependencies on demand - is considered an anti-pattern because it hides dependencies: the class’s true needs are no longer visible in its signature but buried in its method bodies, so you can’t tell what it depends on without reading all its code, tests must configure a container rather than just pass fakes, failures surface at call time rather than construction time, and the class becomes coupled to the container itself. It also makes it easy to accidentally resolve scoped services from the wrong scope. Constructor injection, by contrast, keeps dependencies declarative and the container’s involvement at the composition root only. There are rare legitimate uses of resolving from the provider (a factory that must create instances dynamically, or bridging a scope in a background service), but as a general pattern for getting a class’s collaborators, constructor injection is correct and service location should be avoided. In short, constructor injection makes dependencies explicit, testable, and validated; service location hides them and couples code to the container.

Principal Engineer Question

How do you organize DI registrations and prevent lifetime bugs in a large application?

I keep the composition root thin and push wiring into per-module registration extension methods, so each bounded context or feature owns and encapsulates its service registrations (services.AddPaymentsModule()), keepingProgram.csreadable and letting modules expose only their public contracts while registering internals as internal types. This modular organization prevents the registration file from becoming an unmaintainable dumping ground and keeps dependencies aligned with architectural boundaries. On lifetimes, I standardize conventions - DbContexts and units of work scoped, stateless services singleton, cheap stateless helpers transient - and I document them so teams don’t guess. Crucially, I turn on the container’s validation:ValidateScopesandValidateOnBuildso that captive dependencies (scoped-into-singleton) and unresolvable graphs are caught at application startup and fail the deployment, rather than surfacing as intermittent data-corruption bugs in production under load - this single setting eliminates a whole class of the most damaging DI bugs. For long-lived or background services that need scoped services, I mandate theIServiceScopeFactory-per-unit-of-work pattern rather than direct injection. I avoid over-registration and over-abstraction (interfaces with a single implementation and no seam add cost without benefit), avoid the service-locator pattern, and watch for constructors with too many dependencies as an SRP smell. I also keep registration deterministic and testable, sometimes adding a test that builds the provider and validates the whole graph. The result is that wiring documents the architecture’s boundaries, lifetimes follow clear conventions, and the most dangerous lifetime mistakes are caught automatically at startup - so DI simplifies the architecture rather than becoming a source of subtle production failures.

4.6 Production Scenario

A large enterprise API shows memory growth and intermittent data errors after deployment. Analysis reveals a singleton cache service that accidentally injected a scopedDbContext- a captive dependency sharing one context across all requests. The team fixes it by having the singleton create a scope per operation viaIServiceScopeFactory, and enablesValidateScopesso any future captive dependency fails at startup rather than corrupting data in production.

Chapter Revision Notes

  • DI supplies collaborators from the container; prefer constructor injection over the service locator.
  • ServiceCollection registers services; ServiceProvider resolves and builds object graphs.
  • Match lifetimes to state: transient (stateless helpers), scoped (per request, DbContext), singleton (shared, stateless).
  • Never capture a scoped service in a singleton - use IServiceScopeFactory; enable ValidateScopes.
  • Organize registrations per module; standardize lifetime conventions.