Dependency Injection: The Service Directory

Dependency Injection: The Service Directory in C#: A guest in a hotel who needs a taxi does not walk to the garage, negotiate with a driver and check the…

The Analogy: The Hotel Concierge

A guest in a hotel who needs a taxi does not walk to the garage, negotiate with a driver and check the insurance. They ask the concierge, and a taxi appears at the door. The guest states a need; the hotel decides how that need is met, and can switch taxi firms without telling a single guest.

A class that writes new SqlOrderRepository("Server=...") inside a method is the guest who went to the garage. It has decided which implementation it wants, how that implementation is configured, and how long it lives — three decisions that have nothing to do with the job the class is supposed to do. Every test of that class now needs a real database, and swapping the repository means editing every caller.

Dependency injection moves those decisions to one place. A class declares what it needs in its constructor — OrderService(IOrderRepository repository, ILogger<OrderService> logger) — and the container supplies them. The container is the concierge: it holds a directory mapping each requested service to a way of producing it, and it knows how long each produced thing should live.

The interesting part is not the wiring, which is mechanical. It is lifetime: whether every guest shares one taxi, whether everyone on one floor shares a taxi, or whether each guest gets a fresh one. Get that wrong and the application either wastes work rebuilding things that could be shared, or shares things that were never designed to be shared — and the second failure mode only appears under load, in production.


Syntax or Core Structure

Three registration methods cover almost everything, and they differ only in how long the produced object lives. This console program — the container ships in the Microsoft.Extensions.DependencyInjection package and is already referenced by every web project — makes the difference visible by numbering every instance it creates:

using Microsoft.Extensions.DependencyInjection;

ServiceCollection services = new ServiceCollection();
services.AddTransient<TransientTicket>();      // a new one every time it is asked for
services.AddScoped<ScopedTicket>();            // one per scope, which means one per request
services.AddSingleton<SingletonTicket>();      // one for the lifetime of the container

using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);

for (int pass = 1; pass <= 2; pass++)
{
    using IServiceScope scope = provider.CreateScope();
    IServiceProvider sp = scope.ServiceProvider;

    Console.WriteLine("scope " + pass);
    Console.WriteLine("  transient  " + sp.GetRequiredService<TransientTicket>()
                                      + "  " + sp.GetRequiredService<TransientTicket>());
    Console.WriteLine("  scoped     " + sp.GetRequiredService<ScopedTicket>()
                                      + "  " + sp.GetRequiredService<ScopedTicket>());
    Console.WriteLine("  singleton  " + sp.GetRequiredService<SingletonTicket>()
                                      + "  " + sp.GetRequiredService<SingletonTicket>());
}

try
{
    provider.GetRequiredService<ScopedTicket>();   // the root provider is not a scope
}
catch (InvalidOperationException ex)
{
    Console.WriteLine("root resolve -> " + ex.GetType().Name);
}

abstract class Ticket
{
    private static int issued;

    protected Ticket() => Number = Interlocked.Increment(ref issued);

    public int Number { get; }

    public override string ToString() => GetType().Name + "#" + Number;
}

sealed class TransientTicket : Ticket { }
sealed class ScopedTicket : Ticket { }
sealed class SingletonTicket : Ticket { }

Output:

scope 1
  transient  TransientTicket#1  TransientTicket#2
  scoped     ScopedTicket#3  ScopedTicket#3
  singleton  SingletonTicket#4  SingletonTicket#4
scope 2
  transient  TransientTicket#5  TransientTicket#6
  scoped     ScopedTicket#7  ScopedTicket#7
  singleton  SingletonTicket#4  SingletonTicket#4
root resolve -> InvalidOperationException

The instance numbers tell the whole story. Transient produces a new ticket for every single resolve, even twice on the same line. Scoped produces one per scope and hands the same instance back within it, so #3 appears twice in scope 1 and #7 twice in scope 2. The singleton is created once, on first use, and #4 survives both scopes. In ASP.NET Core a scope is created per HTTP request and disposed when the response completes, which is why "scoped" and "per request" are used interchangeably.

The last three lines matter as much as the first six. Asking the root provider for a scoped service is a bug — there is no scope to bound its lifetime, so the instance would live as long as the application — and validateScopes: true turns that bug into an immediate exception. ASP.NET Core switches that validation on automatically in the Development environment and off in Production, which is exactly why this class of mistake tends to be discovered by customers rather than by developers.


Technical Depth: Lifetimes, Registration and Disposal

LifetimeOne instance perGood forDanger
TransientEvery resolveCheap, stateless helpers; validators; mappersAllocation churn if resolved in a loop; disposables pile up until the scope ends
ScopedScope, so per HTTP requestDbContext, unit of work, per-request caches, the current userCaptured by a singleton it becomes application-wide and unsafe
SingletonContainerConfiguration, caches, HTTP clients, expensive factoriesMust be thread-safe; must not hold scoped state

The registration forms

services.AddScoped<IOrderRepository, SqlOrderRepository>();     // interface to implementation
services.AddSingleton<Clock>();                                 // concrete type, self-bound
services.AddSingleton<IClock>(new SystemClock());               // an instance you already have
services.AddScoped<IOrderRepository>(sp =>                      // factory, for anything computed
    new SqlOrderRepository(sp.GetRequiredService<IConfiguration>()["Db:Orders"]!));

services.TryAddSingleton<IClock, SystemClock>();                // only if nobody registered it
services.AddSingleton<IOrderRule, SkuRequiredRule>();           // several implementations of
services.AddSingleton<IOrderRule, QuantityRule>();              // one interface: inject IEnumerable
services.AddKeyedSingleton<IShipper, Courier>("express");       // selected by key at resolve time

Two of these behave in ways worth committing to memory. Registering the same service type twice does not overwrite — the last registration wins for GetRequiredService<T>(), and GetRequiredService<IEnumerable<T>>() returns all of them in registration order. That is the mechanism behind validation rule sets, notification handlers and pipeline behaviours. TryAdd exists so libraries can supply a default without stamping on an application's own choice.

Keyed services, added in .NET 8, cover the case where one interface has several implementations and the caller must pick one by name. The consumer marks the parameter:

public sealed class OrderShipper(
    [FromKeyedServices("express")] IShipper express,
    [FromKeyedServices("economy")] IShipper economy)
{
    // ...
}

Captive dependencies

A singleton that takes a scoped service in its constructor captures the first instance it is given and keeps it forever. This is the single most common DI bug in ASP.NET Core, and it usually appears as a DbContext shared by every request in the process: change tracking that never resets, ObjectDisposedException under load, and rows from one user's request appearing in another's.

The container can catch it at startup rather than at runtime:

builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes = true;     // no scoped services from the root provider
    options.ValidateOnBuild = true;    // walk every registration at startup, not on first request
});

ValidateOnBuild is the cheaper insurance of the two: it constructs the call site for every registration when the host starts, so a missing or mis-scoped dependency fails the deployment instead of the first request that touches it. Both are worth turning on in every environment.

Disposal

Registered howDisposed by the container?When
AddScoped<T>()YesWhen the scope is disposed, so at the end of the request
AddTransient<T>()Yes, if IDisposableWhen the resolving scope is disposed, not when you stop using it
AddSingleton<T>()YesWhen the root provider is disposed at shutdown
AddSingleton(instance)NoNever — you created it, so you dispose it

The transient row is a trap. A disposable transient resolved from a long-lived scope is held by that scope until it ends, so resolving thousands of them in a background loop is a memory leak that looks nothing like one. Either avoid disposable transients or create a short scope around the work.

Getting a scoped service from a singleton

The correct tool is IServiceScopeFactory, which is itself a singleton. A background worker creates a scope per unit of work, resolves what it needs inside, and disposes the scope when the item is done — exactly mirroring what the web host does per request. Reaching for HttpContext.RequestServices or a static provider instead is the service locator pattern: it compiles, hides the dependency from the constructor, and defers every wiring mistake to runtime.


Real World Example: The Worker That Held a DbContext

A queue processor is registered as a singleton because there should be one of it. It needs a repository, which is scoped because it wraps a database connection. Written naively, the application starts and then misbehaves hours later. Written with a scope factory, each message gets its own clean unit of work — and the container proves the naive version wrong before the process ever serves traffic.

using Microsoft.Extensions.DependencyInjection;

Log log = new Log();

// --- The naive wiring: a singleton that asks for a scoped service directly. ---
ServiceCollection naive = new ServiceCollection();
naive.AddSingleton(log);
naive.AddScoped<IOrderSink, OrderRepository>();
naive.AddSingleton<CaptiveProcessor>();

try
{
    naive.BuildServiceProvider(new ServiceProviderOptions
    {
        ValidateScopes = true,
        ValidateOnBuild = true
    });

    log.Add("guard   built without complaint");
}
catch (AggregateException ex)
{
    log.Add("guard   " + ex.GetType().Name + " / " + ex.InnerExceptions[0].GetType().Name);
}

// --- The correct wiring: the singleton takes a scope factory instead. ---
ServiceCollection services = new ServiceCollection();
services.AddSingleton(log);                    // an instance, so the container will not dispose it
services.AddScoped<IOrderSink, OrderRepository>();
services.AddTransient<IOrderRule, SkuRequiredRule>();
services.AddTransient<IOrderRule, QuantityRule>();
services.AddTransient<OrderValidator>();
services.AddSingleton<QueueProcessor>();

using ServiceProvider provider = services.BuildServiceProvider(new ServiceProviderOptions
{
    ValidateScopes = true,
    ValidateOnBuild = true
});

QueueProcessor processor = provider.GetRequiredService<QueueProcessor>();
processor.Process(new[]
{
    new Message("BOLT-01", 2),
    new Message("", 5),
    new Message("NUT-07", 0)
});

foreach (string line in log.Lines)
{
    Console.WriteLine(line);
}

sealed record Message(string Sku, int Quantity);

interface IOrderRule
{
    string? Check(Message message);        // null means "no complaint"
}

sealed class SkuRequiredRule : IOrderRule
{
    public string? Check(Message message) =>
        string.IsNullOrWhiteSpace(message.Sku) ? "sku is required" : null;
}

sealed class QuantityRule : IOrderRule
{
    public string? Check(Message message) =>
        message.Quantity is < 1 or > 100 ? "quantity must be 1-100" : null;
}

sealed class OrderValidator
{
    private readonly IOrderRule[] rules;

    // Every registration of IOrderRule arrives here, in registration order.
    public OrderValidator(IEnumerable<IOrderRule> rules) => this.rules = rules.ToArray();

    public int RuleCount => rules.Length;

    public string? FirstFailure(Message message)
    {
        foreach (IOrderRule rule in rules)
        {
            string? complaint = rule.Check(message);
            if (complaint is not null)
            {
                return rule.GetType().Name + ": " + complaint;
            }
        }

        return null;
    }
}

interface IOrderSink
{
    void Save(Message message);
}

sealed class OrderRepository : IOrderSink, IDisposable
{
    private static int created;

    private readonly Log log;
    private readonly int id;

    public OrderRepository(Log log)
    {
        this.log = log;
        this.id = Interlocked.Increment(ref created);
    }

    public static int Created => created;

    public void Save(Message message) =>
        log.Add("save    " + message.Sku + " x" + message.Quantity + "  by repo#" + id);

    public void Dispose() => log.Add("dispose repo#" + id);
}

// The bug the container refuses to build: a singleton holding a scoped service.
sealed class CaptiveProcessor
{
    public CaptiveProcessor(IOrderSink sink) { }
}

sealed class QueueProcessor
{
    private readonly IServiceScopeFactory scopeFactory;
    private readonly Log log;

    public QueueProcessor(IServiceScopeFactory scopeFactory, Log log)
    {
        this.scopeFactory = scopeFactory;
        this.log = log;
    }

    public void Process(IEnumerable<Message> batch)
    {
        int number = 0;

        foreach (Message message in batch)
        {
            number++;

            // One scope per message: the same unit-of-work boundary a request gets.
            using IServiceScope scope = scopeFactory.CreateScope();
            log.Add("scope   " + number + " open");

            OrderValidator validator = scope.ServiceProvider.GetRequiredService<OrderValidator>();
            string? failure = validator.FirstFailure(message);

            if (failure is not null)
            {
                log.Add("check   " + Describe(message) + "  rejected by " + failure);
                continue;                  // the repository is never resolved, so none is created
            }

            log.Add("check   " + Describe(message) + "  ok (" + validator.RuleCount + " rules)");
            scope.ServiceProvider.GetRequiredService<IOrderSink>().Save(message);
        }

        log.Add("done    repositories created: " + OrderRepository.Created);
    }

    private static string Describe(Message message) =>
        (message.Sku.Length == 0 ? "(blank)" : message.Sku) + " x" + message.Quantity;
}

sealed class Log
{
    private readonly List<string> lines = new List<string>();

    public IReadOnlyList<string> Lines => lines;

    public void Add(string line) => lines.Add(line);
}

Output:

guard   AggregateException / InvalidOperationException
scope   1 open
check   BOLT-01 x2  ok (2 rules)
save    BOLT-01 x2  by repo#1
dispose repo#1
scope   2 open
check   (blank) x5  rejected by SkuRequiredRule: sku is required
scope   3 open
check   NUT-07 x0  rejected by QuantityRule: quantity must be 1-100
done    repositories created: 1

The first line is the most valuable one in the program. CaptiveProcessor is perfectly legal C# and would have run happily for hours, quietly sharing one repository across every message in the process; ValidateOnBuild combined with ValidateScopes refuses to hand back a provider at all. The failure arrives as an AggregateException because the validator collects every problem it finds rather than stopping at the first, which matters on a real service with fifty registrations.

QueueProcessor fixes it by depending on IServiceScopeFactory — a singleton — and creating a scope per message. Each scope owns its own IOrderSink, and the dispose repo#1 line proves the container tore it down at the end of the iteration without anybody writing a finally. That is the same lifecycle an HTTP request gets, so a repository written for the web works unchanged in a worker.

Notice what did not happen for messages two and three: no repository was created, because the code resolves the sink only after validation passes. Resolution is lazy, so a rejected message costs a validator and nothing else. On a real service where the repository opens a database connection, that ordering is the difference between a validation error costing microseconds and costing a connection from the pool.

The rule set shows the other half of the container's value. OrderValidator asks for IEnumerable<IOrderRule> and receives every registered rule in registration order, so adding a third rule is one line in Program.cs and no change to the validator, the processor or the repository. Log is registered as an instance to make one more point concrete: the container did not dispose it at shutdown, because it did not create it. Ownership follows creation.


Common Mistakes

  1. Injecting a scoped service into a singleton. The singleton captures the first instance and keeps it for the life of the process. Depend on IServiceScopeFactory and create a scope per unit of work instead, and switch on ValidateScopes and ValidateOnBuild so the container refuses the wiring at startup.
  2. Registering a DbContext or connection as a singleton to "save allocations". These types are documented as not thread-safe. A single instance shared across concurrent requests produces interleaved change tracking and ObjectDisposedException at random, and the allocation it saves is irrelevant next to the query it runs.
  3. Resolving services with provider.GetRequiredService from inside business logic. That is the service locator pattern: the dependency vanishes from the constructor, so nothing reveals it until the code runs. Declare dependencies as parameters and let the container fill them.
  4. Mutable state on a singleton without synchronisation. A Dictionary field on a singleton is shared by every concurrent request and can corrupt or throw during resize. Use ConcurrentDictionary, an immutable snapshot, or a lock — and be deliberate about which.
  1. Assuming a second registration replaces the first. Registering IClock twice leaves both in the collection; GetRequiredService<IClock>() returns the last one and IEnumerable<IClock> returns both. Use TryAdd for defaults and Replace when the intent really is substitution.
  2. New-ing up dependencies inside a class that is otherwise injected. new HttpClient() in a method defeats the container, exhausts sockets, and cannot be substituted in a test. Inject IHttpClientFactory or the typed client and let the infrastructure own the lifetime.
  3. Constructors that do work. A constructor called by the container should assign fields and nothing else — no file reads, no queries, no thread starts. Expensive initialisation belongs in a factory registration or an IHostedService, where failures are visible at startup and can be awaited.
  4. A constructor with a dozen parameters treated as a DI problem. The container is not the difficulty; the class is doing a dozen jobs. Split it, or introduce a facade that genuinely owns a cohesive slice of the work rather than passing the parameter list along.

Best Practices

  • Default to the shortest lifetime that works: transient unless there is a reason, scoped for anything touching a request or a transaction, singleton only for things that are immutable or explicitly thread-safe.
  • Register interfaces, not concrete types, for anything that has a substitute worth writing — and skip the interface for a leaf type nobody will ever replace.
  • Turn on ValidateScopes and ValidateOnBuild in every environment. A deployment that fails to start beats a service that fails on the request that matters.
  • Group registrations into AddOrdersModule()-style extension methods per feature, so Program.cs stays a table of contents rather than a hundred lines of wiring.
  • Take IServiceScopeFactory in singletons and background services, and create one scope per message, per timer tick, or per item — never one scope for the whole worker.
  • Keep IServiceProvider out of constructors. If a class needs to choose an implementation at runtime, inject IEnumerable<T>, a keyed service, or a small factory interface you control.
  • Let the container own disposal for what it created, and dispose instances you registered yourself. Never call Dispose on an injected dependency; the scope that created it will.
  • Prefer constructor injection over property injection everywhere. A constructor parameter is a compile-time contract; a settable property is a hope that somebody remembered.

Practice Exercises

  1. Watch the lifetimes. Extend the ticket program with a fourth service that takes all three tickets in its constructor, resolve it twice in one scope and once in another, and print which ticket numbers it received each time. Explain why the transient number changes while the singleton number does not.
  2. Break the guard deliberately. Register CaptiveProcessor in the working container and build it with ValidateScopes = false. Show that the build succeeds, then resolve it twice from two different scopes and print the repository id it holds, proving that both scopes share one instance.
  3. Add a rule without touching a class. Add a SkuFormatRule that requires an uppercase prefix, a dash and two digits, register it, and show that OrderValidator now reports three rules and rejects bolt-1 — with no edit to the validator, the processor or the repository.
  4. Swap an implementation by key. Register two IOrderSink implementations under the keys "sql" and "memory", resolve one by key based on a configuration value, and print which implementation handled each message. Then describe how you would test the processor with the in-memory sink and no database at all.