Dependency injection with Microsoft.Extensions.DependencyInjection

suggest change

Microsoft.Extensions.DependencyInjection is the dependency injection (DI) container that ships with .NET. ASP.NET Core, the Generic Host, worker services, Entity Framework Core, logging, HttpClientFactory and the options system are all built on it, so in modern .NET it's the default choice. You no longer need a third-party container like Unity or MEF for most apps.

The model is simple:

  1. You register services in an IServiceCollection: "when someone asks for IClock, give them a SystemClock, and keep one for the whole app".
  2. You build an IServiceProvider from it.
  3. The provider creates objects for you. It looks at the constructor, resolves every parameter (recursively), and calls it.

Your classes only declare what they need as constructor parameters. They never call new on their dependencies or look them up in a global registry.

This article covers the container as of .NET 10. Keyed services need .NET 8 or later; everything else works on .NET 6 and later. The examples are C# 14 file-based programs: save the code as app.cs and run dotnet run app.cs. The #:package line at the top pulls the NuGet package. In an ASP.NET Core or worker project the package is already referenced.

A first example of a service with constructor injection is in Primary constructors. This article goes further: lifetimes, scopes, the host, keyed services and testing.

Lifetimes: singleton, scoped, transient

Every registration has a lifetime that decides when the container creates a new instance:

To see the difference, each class below numbers its instances:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<SingletonDep>();
services.AddScoped<ScopedDep>();
services.AddTransient<TransientDep>();
services.AddTransient<Consumer>();

using var provider = services.BuildServiceProvider();

for (int s = 1; s <= 2; s++)
{
    using var scope = provider.CreateScope();
    var a = scope.ServiceProvider.GetRequiredService<Consumer>();
    var b = scope.ServiceProvider.GetRequiredService<Consumer>();
    Console.WriteLine($"scope {s}: {a}");
    Console.WriteLine($"scope {s}: {b}");
}

abstract class Numbered
{
    private static readonly Dictionary<Type, int> Counters = [];
    public int Id { get; }
    protected Numbered()
    {
        Counters.TryGetValue(GetType(), out int n);
        Id = Counters[GetType()] = n + 1;
    }
}

class SingletonDep : Numbered;
class ScopedDep : Numbered;
class TransientDep : Numbered;

class Consumer(SingletonDep single, ScopedDep scoped, TransientDep transient)
{
    public override string ToString() =>
        $"singleton #{single.Id}, scoped #{scoped.Id}, transient #{transient.Id}";
}
scope 1: singleton #1, scoped #1, transient #1
scope 1: singleton #1, scoped #1, transient #2
scope 2: singleton #1, scoped #2, transient #3
scope 2: singleton #1, scoped #2, transient #4

The singleton is shared by everything. The scoped instance is shared within a scope (both Consumers in scope 1 get scoped #1) and replaced in the next one. Each transient is new.

How to choose:

Consumer uses a primary constructor: class Consumer(SingletonDep single, ...). That's the usual way to write DI services in C# 12 and later. The container treats it like any other constructor.

Registering services

There are several ways to tell the container how to make a service:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

var services = new ServiceCollection();

// 1. type mapping
services.AddSingleton<INotifier, EmailNotifier>();
// 2. a second registration for the same service type
services.AddSingleton<INotifier, SmsNotifier>();
// 3. TryAdd does nothing if INotifier is already registered
services.TryAddSingleton<INotifier, PushNotifier>();
// 4. factory: full control over construction
services.AddSingleton<Settings>(sp => new Settings("smtp.example.com", 587));
// 5. an existing instance
services.AddSingleton(TimeProvider.System);
// 6. open generic: one registration for every T
services.AddScoped(typeof(IRepository<>), typeof(MemoryRepository<>));

using var provider = services.BuildServiceProvider();

Console.WriteLine($"single:  {provider.GetRequiredService<INotifier>().GetType().Name}");
foreach (var n in provider.GetServices<INotifier>())
    Console.WriteLine($"all:     {n.GetType().Name}");
Console.WriteLine($"factory: {provider.GetRequiredService<Settings>()}");
Console.WriteLine($"generic: {provider.GetRequiredService<IRepository<Order>>().GetType().Name}");
Console.WriteLine($"missing: {provider.GetService<IDisposable>() is null}");
try
{
    provider.GetRequiredService<IDisposable>();
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

interface INotifier { void Send(string msg); }
class EmailNotifier : INotifier { public void Send(string msg) { } }
class SmsNotifier : INotifier { public void Send(string msg) { } }
class PushNotifier : INotifier { public void Send(string msg) { } }
record Settings(string Host, int Port);
record Order(int Id);
interface IRepository<T> { void Add(T item); }
class MemoryRepository<T> : IRepository<T>
{
    private readonly List<T> _items = [];
    public void Add(T item) => _items.Add(item);
}
single:  SmsNotifier
all:     EmailNotifier
all:     SmsNotifier
factory: Settings { Host = smtp.example.com, Port = 587 }
generic: MemoryRepository`1
missing: True
No service for type 'System.IDisposable' has been registered.

What this shows:

You usually group registrations in an extension method on IServiceCollection, like services.AddShop() in the testing section below. That's the same pattern as the framework's AddLogging(), AddHttpClient() and AddDbContext().

The captive dependency bug

The lifetime rule to remember: a service must not depend on a service with a shorter lifetime. A singleton that takes a scoped service in its constructor keeps that one instance forever. The scoped service becomes "captive" and is shared by every request:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddScoped<UnitOfWork>();
services.AddSingleton<PriceCache>();   // bug: singleton depends on scoped

// default: no validation
using (var provider = services.BuildServiceProvider())
{
    for (int i = 1; i <= 2; i++)
    {
        using var scope = provider.CreateScope();
        var uow = scope.ServiceProvider.GetRequiredService<UnitOfWork>();
        var cache = scope.ServiceProvider.GetRequiredService<PriceCache>();
        Console.WriteLine($"request {i}: scope has {uow}, cache holds {cache.Uow}");
    }
}

// with validation
try
{
    services.BuildServiceProvider(new ServiceProviderOptions
    {
        ValidateScopes = true,
        ValidateOnBuild = true,
    });
}
catch (AggregateException e)
{
    foreach (var inner in e.InnerExceptions)
        Console.WriteLine(inner.Message);
}

class UnitOfWork : IDisposable
{
    private static int _next;
    private readonly int _id = ++_next;
    public bool Disposed { get; private set; }
    public void Dispose() => Disposed = true;
    public override string ToString() => $"UnitOfWork #{_id}{(Disposed ? " (disposed!)" : "")}";
}

class PriceCache(UnitOfWork uow)
{
    public UnitOfWork Uow => uow;
}
request 1: scope has UnitOfWork #1, cache holds UnitOfWork #2
request 2: scope has UnitOfWork #3, cache holds UnitOfWork #2
Error while validating the service descriptor 'ServiceType: PriceCache Lifetime: Singleton ImplementationType: PriceCache': Cannot consume scoped service 'UnitOfWork' from singleton 'PriceCache'.

Without validation the container happily builds PriceCache once, with a UnitOfWork from the root provider. Every request then uses the same UnitOfWork #2, and it's only disposed when the whole app shuts down. With an EF Core DbContext this shows up as threading exceptions under load, stale data, or a context that grows until it runs out of memory.

The same mistake happens with transients: a transient captured by a singleton is effectively a singleton too. The container doesn't flag that, because transient-in-singleton is often fine for stateless services. It's a problem when the transient isn't thread-safe.

The fixes:

Scope validation

ServiceProviderOptions has two switches:

Resolving a scoped service outside a scope is also caught by ValidateScopes:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddScoped<UnitOfWork>();

using var provider = services.BuildServiceProvider(validateScopes: true);
try
{
    provider.GetRequiredService<UnitOfWork>();
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

using var scope = provider.CreateScope();
Console.WriteLine(scope.ServiceProvider.GetRequiredService<UnitOfWork>());

class UnitOfWork;
Cannot resolve scoped service 'UnitOfWork' from root provider.
UnitOfWork

And ValidateOnBuild finds a forgotten registration before anything runs:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddScoped<Checkout>();   // forgot IPaymentGateway

try
{
    services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true });
}
catch (AggregateException e)
{
    Console.WriteLine(e.InnerExceptions[0].Message);
}

interface IPaymentGateway { void Charge(decimal amount); }
class Checkout(IPaymentGateway gateway)
{
    public void Pay(decimal amount) => gateway.Charge(amount);
}
Error while validating the service descriptor 'ServiceType: Checkout Lifetime: Scoped ImplementationType: Checkout': Unable to resolve service for type 'IPaymentGateway' while attempting to activate 'Checkout'.

ValidateOnBuild can't see dependencies that are resolved inside a factory lambda or with GetRequiredService at runtime; it only checks constructor parameters.

The Generic Host

In real apps you rarely create a ServiceCollection yourself. Host.CreateApplicationBuilder (in Microsoft.Extensions.Hosting) sets up configuration (appsettings.json, environment variables, command line), logging and DI in one call, and gives you builder.Services to register your services. ASP.NET Core's WebApplication.CreateBuilder works the same way.

This worker reads options from configuration, and a hosted service sends mail in batches, each batch in its own scope:

#:package Microsoft.Extensions.Hosting@10.0.13

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.ClearProviders();   // keep the output short
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
    ["Mail:Sender"] = "noreply@example.com",
    ["Mail:BatchSize"] = "2",
});

builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"));
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<IMailQueue, MemoryMailQueue>();
builder.Services.AddScoped<MailSender>();
builder.Services.AddHostedService<MailWorker>();

using var host = builder.Build();
Console.WriteLine($"environment: {builder.Environment.EnvironmentName}");
await host.RunAsync();
Console.WriteLine("host stopped");

class MailOptions
{
    public string Sender { get; set; } = "";
    public int BatchSize { get; set; } = 10;
}

interface IMailQueue { IReadOnlyList<string> Take(int count); }

class MemoryMailQueue : IMailQueue, IDisposable
{
    private static int _next;
    private readonly int _id = ++_next;
    private readonly Queue<string> _q = new(["ann@a.com", "bob@b.com", "cy@c.com"]);

    public IReadOnlyList<string> Take(int count) =>
        [.. Enumerable.Range(0, Math.Min(count, _q.Count)).Select(_ => _q.Dequeue())];

    public void Dispose() => Console.WriteLine($"  queue #{_id} disposed");
}

class MailSender(IMailQueue queue, IOptions<MailOptions> options)
{
    private readonly MailOptions _opts = options.Value;

    public void SendBatch()
    {
        foreach (var to in queue.Take(_opts.BatchSize))
            Console.WriteLine($"  {_opts.Sender} -> {to}");
    }
}

// hosted services are singletons: create a scope for each unit of work
class MailWorker(IServiceScopeFactory scopes, IHostApplicationLifetime lifetime)
    : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        for (int run = 1; run <= 2; run++)
        {
            Console.WriteLine($"run {run}:");
            using var scope = scopes.CreateScope();
            scope.ServiceProvider.GetRequiredService<MailSender>().SendBatch();
        }
        lifetime.StopApplication();
        return Task.CompletedTask;
    }
}
environment: Production
run 1:
  noreply@example.com -> ann@a.com
  noreply@example.com -> bob@b.com
  queue #1 disposed
run 2:
  noreply@example.com -> ann@a.com
  noreply@example.com -> bob@b.com
  queue #2 disposed
host stopped

Notes:

Validation is on in Development

The host turns on ValidateScopes and ValidateOnBuild only when the environment is Development. The environment comes from the DOTNET_ENVIRONMENT (or, in ASP.NET Core, ASPNETCORE_ENVIRONMENT) variable and is Production when it's not set:

#:package Microsoft.Extensions.Hosting@10.0.13

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

foreach (var env in new[] { "Production", "Development" })
{
    var builder = Host.CreateApplicationBuilder(
        new HostApplicationBuilderSettings { EnvironmentName = env });
    builder.Services.AddScoped<UnitOfWork>();
    builder.Services.AddSingleton<PriceCache>();
    try
    {
        using var host = builder.Build();
        Console.WriteLine($"{env}: built fine, bug not detected");
    }
    catch (AggregateException e)
    {
        Console.WriteLine($"{env}: {e.InnerExceptions[0].Message}");
    }
}

class UnitOfWork;
class PriceCache(UnitOfWork uow) { public UnitOfWork Uow => uow; }
Production: built fine, bug not detected
Development: Error while validating the service descriptor 'ServiceType: PriceCache Lifetime: Singleton ImplementationType: PriceCache': Cannot consume scoped service 'UnitOfWork' from singleton 'PriceCache'.

So run your app in Development locally (launchSettings.json in new projects does it for you), or turn validation on everywhere:

builder.ConfigureContainer(new DefaultServiceProviderFactory(new ServiceProviderOptions
{
    ValidateScopes = true,
    ValidateOnBuild = true,
}));

Validation has a startup cost proportional to the number of registrations, which is why it's off in Production by default. For most apps it's small.

Disposal

The container disposes the IDisposable (and IAsyncDisposable) objects it created: scoped and transient ones when their scope is disposed, singletons when the provider is disposed. Objects you passed in as instances are yours to dispose:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<Cache>();
services.AddSingleton(new Connection());   // created by you, owned by you
services.AddScoped<DbContext>();
services.AddTransient<Report>();

using (var provider = services.BuildServiceProvider())
{
    provider.GetRequiredService<Cache>();
    provider.GetRequiredService<Connection>();
    using (var scope = provider.CreateScope())
    {
        scope.ServiceProvider.GetRequiredService<DbContext>();
        scope.ServiceProvider.GetRequiredService<Report>();
        scope.ServiceProvider.GetRequiredService<Report>();
        Console.WriteLine("-- end of scope");
    }
    Console.WriteLine("-- end of provider");
}

abstract class Res : IDisposable
{
    private static int _next;
    private readonly string _name;
    protected Res() => _name = $"{GetType().Name} #{++_next}";
    public void Dispose() => Console.WriteLine($"disposed {_name}");
}
class Cache : Res;
class Connection : Res;
class DbContext : Res;
class Report : Res;
-- end of scope
disposed Report #5
disposed Report #4
disposed DbContext #3
-- end of provider
disposed Cache #2

Connection #1 was created with new and registered as an instance, so the container never disposes it. Objects are disposed in reverse order of creation.

Watch out for disposable transients resolved from the root provider: the provider keeps a reference to each one so it can dispose it at shutdown, and in a long-running app that's a memory leak. Resolve them from a scope instead.

If a service implements only IAsyncDisposable, dispose its scope with await using var scope = provider.CreateAsyncScope();. A synchronous Dispose on that scope throws.

Keyed services

Sometimes you have several implementations of one interface and a consumer needs a specific one. Before .NET 8 you had to write a factory or inject IEnumerable<T> and pick. .NET 8 added keyed services: register with a key, and ask for a key with [FromKeyedServices]:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddKeyedSingleton<IStorage, DiskStorage>("local");
services.AddKeyedSingleton<IStorage, CloudStorage>("cloud");
services.AddKeyedSingleton<IStorage, CloudStorage>("archive");
services.AddTransient<BackupJob>();

using var provider = services.BuildServiceProvider();

provider.GetRequiredService<BackupJob>().Run("report.pdf");

// resolve by key directly
var cloud = provider.GetRequiredKeyedService<IStorage>("cloud");
Console.WriteLine($"cloud key -> {cloud.Name}");

// a keyed service is not visible without its key
Console.WriteLine($"no key -> {provider.GetService<IStorage>()?.Name ?? "null"}");

interface IStorage { string Name { get; } void Save(string file); }

class DiskStorage : IStorage
{
    public string Name => "disk";
    public void Save(string file) => Console.WriteLine($"disk: saved {file}");
}

class CloudStorage([ServiceKey] string key) : IStorage
{
    public string Name => $"cloud({key})";
    public void Save(string file) => Console.WriteLine($"{Name}: uploaded {file}");
}

class BackupJob(
    [FromKeyedServices("local")] IStorage primary,
    [FromKeyedServices("archive")] IStorage secondary)
{
    public void Run(string file)
    {
        primary.Save(file);
        secondary.Save(file);
    }
}
disk: saved report.pdf
cloud(archive): uploaded report.pdf
cloud key -> cloud(cloud)
no key -> null

Use keyed services sparingly. If a consumer picks an implementation by key, it knows about deployment details. Often a separate interface (IArchiveStorage) or a small factory is clearer.

Testing

Constructor injection makes classes easy to test, and most tests don't need the container at all. Where the container helps is checking that the registrations are complete and running integration tests with one service swapped for a fake:

#:package Microsoft.Extensions.DependencyInjection@10.0.13

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

// 1. unit test: no container, pass fakes to the constructor
var fakeGateway = new FakeGateway();
var checkout = new Checkout(fakeGateway);
checkout.Pay(42m);
Check("unit: gateway charged 42", fakeGateway.Charged.SequenceEqual([42m]));

// 2. the real registrations can be built (catches missing services)
var services = new ServiceCollection().AddShop();
using (services.BuildServiceProvider(new ServiceProviderOptions
       { ValidateOnBuild = true, ValidateScopes = true }))
{
    Check("composition: container builds", true);
}

// 3. integration test: real registrations, one service replaced
var testServices = new ServiceCollection().AddShop();
var fake = new FakeGateway();
testServices.Replace(ServiceDescriptor.Singleton<IPaymentGateway>(fake));
using (var provider = testServices.BuildServiceProvider(validateScopes: true))
using (var scope = provider.CreateScope())
{
    scope.ServiceProvider.GetRequiredService<Checkout>().Pay(10m);
    Check("integration: fake got the charge", fake.Charged.SequenceEqual([10m]));
}

static void Check(string name, bool ok) =>
    Console.WriteLine($"{(ok ? "PASS" : "FAIL")} {name}");

static class ShopServiceCollectionExtensions
{
    public static IServiceCollection AddShop(this IServiceCollection services)
    {
        services.AddSingleton<IPaymentGateway, StripeGateway>();
        services.AddScoped<Checkout>();
        return services;
    }
}

interface IPaymentGateway { void Charge(decimal amount); }

class StripeGateway : IPaymentGateway
{
    public void Charge(decimal amount) => throw new InvalidOperationException("real network call");
}

class FakeGateway : IPaymentGateway
{
    public List<decimal> Charged { get; } = [];
    public void Charge(decimal amount) => Charged.Add(amount);
}

class Checkout(IPaymentGateway gateway)
{
    public void Pay(decimal amount) => gateway.Charge(amount);
}
PASS unit: gateway charged 42
PASS composition: container builds
PASS integration: fake got the charge
  1. Unit tests call the constructor directly with fakes. No container, no configuration.
  2. A composition test builds the real registrations with ValidateOnBuild and ValidateScopes. It catches a forgotten registration or a captive dependency in a test run instead of in production. Run it with the same registration method the app uses (AddShop() here).
  3. Integration tests use the real registrations and replace only what talks to the outside world. Replace (from Microsoft.Extensions.DependencyInjection.Extensions) removes the first registration of the service type and adds the new one. RemoveAll<T>() removes all of them. ASP.NET Core's WebApplicationFactory<T> does the same with builder.ConfigureTestServices(services => ...).

In a real project these would be xUnit, NUnit or MSTest tests; the Check helper just keeps the example self-contained.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents