Tutorials / Advanced C# and .NET / Dependency injection and service lifetimes

Dependency injection and service lifetimes

15 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

The problem with new inside classes

Look at this class:

class OrderService
{
    private readonly SqlOrderRepository _repo = new SqlOrderRepository("Server=...");

    public void Place(Order order) { _repo.Save(order); }
}

It works, but it has three problems. It is welded to one repository, so you cannot test it without a database. The connection string is buried inside. And if the repository itself needs other objects, the service must know how to build all of them.

Dependency injection (DI) fixes this with a simple rule: a class does not create the things it needs. It asks for them in its constructor and somebody else supplies them. The "somebody else" is a container that you configure once at the start of the program.

Constructor injection

The class declares what it needs, usually as interfaces. A container reads the constructor, finds registered implementations, builds them (and their dependencies) and passes them in. You almost never call the container yourself apart from at the entry point.

This lesson uses the package Microsoft.Extensions.DependencyInjection. Create a console project and add it with dotnet add package Microsoft.Extensions.DependencyInjection. ASP.NET Core includes the same container, so everything here applies to web apps too.

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<IClock, SystemClock>();
services.AddScoped<IOrderRepository, InMemoryOrderRepository>();
services.AddTransient<OrderService>();
services.AddTransient<IdGenerator>();

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

// Each scope is like one web request
using (IServiceScope scope = provider.CreateScope())
{
    var service = scope.ServiceProvider.GetRequiredService<OrderService>();
    service.Place("Keyboard", 4500m);
    service.Place("Mouse", 1800m);
    Console.WriteLine($"Orders in this scope: {service.Count}");
}

// Lifetimes in action
using (IServiceScope s1 = provider.CreateScope())
using (IServiceScope s2 = provider.CreateScope())
{
    var repoA1 = s1.ServiceProvider.GetRequiredService<IOrderRepository>();
    var repoA2 = s1.ServiceProvider.GetRequiredService<IOrderRepository>();
    var repoB = s2.ServiceProvider.GetRequiredService<IOrderRepository>();
    Console.WriteLine($"Scoped, same scope:      {ReferenceEquals(repoA1, repoA2)}");
    Console.WriteLine($"Scoped, different scope: {ReferenceEquals(repoA1, repoB)}");

    var id1 = s1.ServiceProvider.GetRequiredService<IdGenerator>();
    var id2 = s1.ServiceProvider.GetRequiredService<IdGenerator>();
    Console.WriteLine($"Transient, same instance: {ReferenceEquals(id1, id2)}");

    var clock1 = s1.ServiceProvider.GetRequiredService<IClock>();
    var clock2 = s2.ServiceProvider.GetRequiredService<IClock>();
    Console.WriteLine($"Singleton, same instance: {ReferenceEquals(clock1, clock2)}");
}

interface IClock { DateTime Now { get; } }
class SystemClock : IClock { public DateTime Now => DateTime.Now; }

record OrderRecord(int Id, string Item, decimal Price, DateTime PlacedAt);

interface IOrderRepository
{
    void Add(OrderRecord order);
    int Count { get; }
}

class InMemoryOrderRepository : IOrderRepository
{
    private readonly List<OrderRecord> _orders = new();
    public void Add(OrderRecord order) => _orders.Add(order);
    public int Count => _orders.Count;
}

class IdGenerator
{
    private static int _last;
    public int Next() => Interlocked.Increment(ref _last);
}

class OrderService(IOrderRepository repository, IClock clock, IdGenerator ids)
{
    public int Count => repository.Count;

    public void Place(string item, decimal price)
    {
        var order = new OrderRecord(ids.Next(), item, price, clock.Now);
        repository.Add(order);
        Console.WriteLine($"Placed #{order.Id} {item} at {order.PlacedAt:HH:mm:ss}");
    }
}

Walking through it

OrderService lists three dependencies in its primary constructor and creates none of them. It does not know whether the repository is in memory or SQL, or whether the clock is real or fake. For a unit test, I would pass a fake clock fixed to a known time, and an in-memory repository. That is the real payoff: code that is easy to test and easy to change.

Registration happens in one place. AddSingleton<IClock, SystemClock>() means "when someone asks for IClock, give them SystemClock". The container resolves OrderService, sees that it needs three things, and builds them.

The three lifetimes

LifetimeMeaningTypical use
SingletonOne instance for the life of the applicationClocks, caches, configuration, HTTP client factories
ScopedOne instance per scope; in a web app, per requestDatabase contexts, unit-of-work objects
TransientA new instance every time it is requestedLightweight, stateless services

The program output shows each rule. The repository is shared inside one scope and different across scopes. The IdGenerator is new on each request. The clock is the same everywhere.

The captive dependency bug

A longer-lived service must never depend on a shorter-lived one. A singleton that takes a scoped service in its constructor would keep that one scoped instance forever, long after its request ended. For a database context, that means a context shared by all users and threads, which causes bizarre errors. I passed validateScopes: true when building the provider so the container throws an exception if it detects this mistake. ASP.NET Core turns this check on in the Development environment. It is one of the most useful safety nets in the framework.

Good habits

  • Depend on interfaces only where it brings value, such as external systems, time, randomness and the file system.
  • Keep constructors small. If a class asks for eight dependencies, it does too much.
  • Do not call GetRequiredService inside your own classes. That is the service locator pattern, and it hides what a class needs.
  • Singletons must be thread-safe, because many requests use them at once.

Common mistakes

  • Registering a service and forgetting it. The error "Unable to resolve service for type" names the missing type.
  • Captive dependencies. A singleton holding a scoped service.
  • Storing per-request data in a singleton. It leaks between users.
  • Circular dependencies. A needs B and B needs A. Redesign, usually by extracting a third class.

Try it yourself

  1. Add an IEmailSender interface with a console implementation, register it, and have OrderService send a message after each order.
  2. Write a FixedClock class and use it in place of SystemClock without changing OrderService.
  3. Make a singleton depend on a scoped service and read the exception the container throws.
csharp
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<IClock, SystemClock>();
services.AddScoped<IOrderRepository, InMemoryOrderRepository>();
services.AddTransient<OrderService>();
services.AddTransient<IdGenerator>();

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

// Each scope is like one web request
using (IServiceScope scope = provider.CreateScope())
{
    var service = scope.ServiceProvider.GetRequiredService<OrderService>();
    service.Place("Keyboard", 4500m);
    service.Place("Mouse", 1800m);
    Console.WriteLine($"Orders in this scope: {service.Count}");
}

// Lifetimes in action
using (IServiceScope s1 = provider.CreateScope())
using (IServiceScope s2 = provider.CreateScope())
{
    var repoA1 = s1.ServiceProvider.GetRequiredService<IOrderRepository>();
    var repoA2 = s1.ServiceProvider.GetRequiredService<IOrderRepository>();
    var repoB = s2.ServiceProvider.GetRequiredService<IOrderRepository>();
    Console.WriteLine($"Scoped, same scope:      {ReferenceEquals(repoA1, repoA2)}");
    Console.WriteLine($"Scoped, different scope: {ReferenceEquals(repoA1, repoB)}");

    var id1 = s1.ServiceProvider.GetRequiredService<IdGenerator>();
    var id2 = s1.ServiceProvider.GetRequiredService<IdGenerator>();
    Console.WriteLine($"Transient, same instance: {ReferenceEquals(id1, id2)}");

    var clock1 = s1.ServiceProvider.GetRequiredService<IClock>();
    var clock2 = s2.ServiceProvider.GetRequiredService<IClock>();
    Console.WriteLine($"Singleton, same instance: {ReferenceEquals(clock1, clock2)}");
}

interface IClock { DateTime Now { get; } }
class SystemClock : IClock { public DateTime Now => DateTime.Now; }

record OrderRecord(int Id, string Item, decimal Price, DateTime PlacedAt);

interface IOrderRepository
{
    void Add(OrderRecord order);
    int Count { get; }
}

class InMemoryOrderRepository : IOrderRepository
{
    private readonly List<OrderRecord> _orders = new();
    public void Add(OrderRecord order) => _orders.Add(order);
    public int Count => _orders.Count;
}

class IdGenerator
{
    private static int _last;
    public int Next() => Interlocked.Increment(ref _last);
}

class OrderService(IOrderRepository repository, IClock clock, IdGenerator ids)
{
    public int Count => repository.Count;

    public void Place(string item, decimal price)
    {
        var order = new OrderRecord(ids.Next(), item, price, clock.Now);
        repository.Add(order);
        Console.WriteLine($"Placed #{order.Id} {item} at {order.PlacedAt:HH:mm:ss}");
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account