Skip to the workspace
Pebellslearn by building
ASP.NET Core Basics: Pipeline, Services and Settings  ›  Lesson

Dependency Injection and Service Lifetimes

Framework Basics 16 minClasses ask for what they need in their constructor, the built-in container supplies it, and the registered lifetime decides whether they share one instance per app, per request, or none.

aspnet core / Dependency Injection and Service Lifetimes

Explore each scene at your own pace.

01 · The rule

The rule

Dependency Injection and Service Lifetimes

LoanService needs a database context, a clock and a logger. If it created them with new, you could never swap the real clock for a fake one in a test, and every class would repeat the setup. ASP.NET Core is built around dependency injection instead: classes ask for what they need, and a container hands it over.

The rule

Ask in the constructor, register once, choose a lifetime: singleton, scoped, transient.

A class declares its dependencies as constructor parameters, usually interfaces:

public class LoanService(LibraryDb db, IClock clock)
{
    public async Task<Loan> BorrowAsync(int bookId, int memberId)
    {
        var loan = new Loan(bookId, memberId, due: clock.Today.AddDays(14));
        db.Loans.Add(loan);
        await db.SaveChangesAsync();
        return loan;
    }
}

Program.cs registers each service once with the built-in container, Microsoft.Extensions.DependencyInjection:

builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddDbContext<LibraryDb>(o => o.UseSqlite("Data Source=library.db"));
builder.Services.AddScoped<LoanService>();

When a controller, endpoint or other service asks for LoanService, the container builds it and fills in its constructor — recursively.

The lifetime says how often a new instance is made:

Lifetime New instance… Good for
Singleton once for the whole app stateless helpers, caches, config
Scoped once per HTTP request DbContext and services that use it
Transient every time it is asked for small, cheap, stateless objects

AddDbContext registers the context as scoped.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.