CURRICULUM PREVIEWRevision 1 · Open for reviewReview the full course
CONNECTING THE PIECES8 min read

Dependency injection and lifetimes

Make the object graph explain your boundaries.

Before you begincsharp-foundations

The idea

The composition root is where implementations are selected. The booking use case depends on a store contract, while the host chooses a PostgreSQL adapter. Scoped services are usually tied to a request in ASP.NET Core. A singleton must not capture a scoped dependency.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
builder.Services.AddScoped<IBookingStore, PgBookingStore>();
builder.Services.AddScoped<CreateBooking>();
// Register a thread-safe shared cache as singleton only
// when its dependencies have compatible lifetimes.
Go
store := NewPgBookingStore(pool)
create := NewCreateBooking(store)
// Go wiring is explicit: construct dependencies at startup.

Decisions that matter

  • Constructor injection makes required collaborators visible.
  • A container resolves dependencies; it does not choose good module boundaries for you.
  • Keep service location out of domain code so dependencies remain testable.

Your turn

A singleton report service receives a scoped DbContext in its constructor. Identify the lifetime bug and choose a repair.

Reveal a worked answer

The singleton outlives the request scope and may share a non-thread-safe context. Make the report operation scoped, or create a scope deliberately for each background unit of work. Do not make the context a singleton.

Keep exploring

One more piece connected.

Mark this lesson complete when you can explain the idea.