Dependency Injection & Lifetimes
ASP.NET Core is built around dependency injection (DI). Instead of a class creating the objects it needs with new, it asks for them — usually as constructor parameters — and a central service container supplies them. You register services once in Program.cs, and the framework hands them to endpoints, controllers, middleware and other services.
The benefits are practical: classes depend on interfaces rather than concrete types, so you can swap implementations (a fake email sender in tests, a real one in production) without touching the code that uses them.
Registering services
Registrations go on builder.Services before builder.Build():
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IClock, SystemClock>(); // one for the whole app
builder.Services.AddScoped<ITodoRepository, TodoRepository>(); // one per HTTP request
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>(); // new every time
var app = builder.Build();Each registration maps a service type (what consumers ask for) to an implementation type (what the container creates). The method name chooses the lifetime:
| Method | Lifetime | One instance per… | Typical use |
|---|---|---|---|
AddSingleton |
Singleton | application | caches, configuration wrappers, HttpClient factories, clocks |
AddScoped |
Scoped | HTTP request (scope) | DbContext, repositories, the "current user" |
AddTransient |
Transient | resolution | lightweight, stateless helpers |
Note: Every HTTP request gets its own scope. Scoped services are created at most once inside it and disposed when the request ends.
Injecting services
In a minimal API, list the service as a handler parameter. The framework sees that the type is registered and resolves it from the request's scope:
app.MapGet("/todos", (ITodoRepository repo) => repo.GetAll());
app.MapPost("/todos/{id}/remind", (int id, ITodoRepository repo, IEmailFormatter fmt) =>
{
var todo = repo.Find(id);
return todo is null ? Results.NotFound() : Results.Ok(fmt.Reminder(todo));
});In classes — controllers, services, middleware — use constructor injection. A primary constructor (C# 12) keeps it short:
public class TodoRepository(AppDbContext db, ILogger<TodoRepository> logger) : ITodoRepository
{
public List<Todo> GetAll()
{
logger.LogInformation("Loading all todos");
return db.Todos.ToList();
}
}The container builds the whole graph: to create TodoRepository it first creates AppDbContext and an ILogger<TodoRepository>, which the framework registers for you.
Seeing lifetimes in action
The container is not magic. Here is a tiny hand-built version that supports the three lifetimes. Every created object gets a sequential ID so you can see when the same instance is reused:
using System;
using System.Collections.Generic;
var services = new MiniContainer();
services.Add<Clock>(Lifetime.Singleton);
services.Add<Repository>(Lifetime.Scoped);
services.Add<Formatter>(Lifetime.Transient);
for (int request = 1; request <= 2; request++)
{
var scope = services.CreateScope();
Console.WriteLine(quot;Request {request}:");
Console.WriteLine(quot; Clock {scope.Get<Clock>().Id} {scope.Get<Clock>().Id}");
Console.WriteLine(quot; Repository {scope.Get<Repository>().Id} {scope.Get<Repository>().Id}");
Console.WriteLine(quot; Formatter {scope.Get<Formatter>().Id} {scope.Get<Formatter>().Id}");
}
enum Lifetime { Singleton, Scoped, Transient }
abstract class Service
{
static int next = 1;
public int Id { get; } = next++;
}
class Clock : Service { }
class Repository : Service { }
class Formatter : Service { }
class MiniContainer
{
readonly Dictionary<Type, Lifetime> registrations = new();
readonly Dictionary<Type, object> singletons = new();
public void Add<T>(Lifetime lifetime) where T : new() => registrations[typeof(T)] = lifetime;
public Scope CreateScope() => new Scope(this);
public class Scope
{
readonly MiniContainer root;
readonly Dictionary<Type, object> scoped = new();
public Scope(MiniContainer root) => this.root = root;
public T Get<T>() where T : new()
{
var type = typeof(T);
switch (root.registrations[type])
{
case Lifetime.Singleton:
if (!root.singletons.ContainsKey(type)) root.singletons[type] = new T();
return (T)root.singletons[type];
case Lifetime.Scoped:
if (!scoped.ContainsKey(type)) scoped[type] = new T();
return (T)scoped[type];
default:
return new T();
}
}
}
}Request 1:
Clock 1 1
Repository 2 2
Formatter 3 4
Request 2:
Clock 1 1
Repository 5 5
Formatter 6 7
The singleton keeps ID 1 forever, the scoped repository is shared within a request but new for the next one, and the transient formatter is new on every Get.
The captive dependency pitfall
A service must never depend on something with a shorter lifetime. If a singleton takes a scoped DbContext in its constructor, that one DbContext is captured for the life of the app — shared across requests and threads, which is a serious bug.
| Consumer → dependency | Allowed? |
|---|---|
| Transient → anything | Yes |
| Scoped → Scoped or Singleton | Yes |
| Singleton → Singleton | Yes |
| Singleton → Scoped | No (captive dependency) |
In the Development environment ASP.NET Core turns on scope validation, so the mistake fails fast at startup:
$ dotnet run --urls http://localhost:5000Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: ReportCache Lifetime: Singleton ImplementationType: ReportCache': Cannot consume scoped service 'AppDbContext' from singleton 'ReportCache'.)
If a singleton genuinely needs scoped work (for example a background job), inject IServiceScopeFactory and create a scope yourself:
public class ReportCache(IServiceScopeFactory scopes)
{
public async Task RefreshAsync()
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// ... use db, then the scope disposes it
}
}Keyed services
Since .NET 8 you can register several implementations of one interface under different keys and pick one with [FromKeyedServices]:
builder.Services.AddKeyedSingleton<IStorage, DiskStorage>("disk");
builder.Services.AddKeyedSingleton<IStorage, CloudStorage>("cloud");
app.MapGet("/backup", ([FromKeyedServices("cloud")] IStorage storage) => storage.Describe());$ curl -s localhost:5000/backupSaving to cloud bucket 'backups'
Without keys, registering the same interface twice means the last registration wins for a single injection, while injecting IEnumerable<IStorage> gives you all of them in registration order.
Tip: Prefer constructor/parameter injection over calling
app.Services.GetRequiredService<T>()everywhere. Pulling services out of the container manually (the "service locator" style) hides a class's real dependencies.
Test yourself
Which lifetime should an EF Core DbContext normally have in a web app?
- Singleton
- Transient
- Scoped
- Static
What is a captive dependency?
- A singleton that depends on a scoped service and keeps it alive too long
- A service registered with a key
- A transient service injected into a controller
- A service that is never used
A transient service is requested three times during one HTTP request. How many instances are created?
- 1
- 3
- 0 until the request ends
- 1 per thread