C# and .NET • Modern C# baseline
Dependency Injection and Application Composition
Build an application by composing services with explicit lifetimes and dependencies.
Dependency injection moves construction decisions to a composition root. Singleton services live for the application lifetime, scoped services typically live for a request, and transient services are created each time requested. A singleton must not capture a shorter-lived scoped dependency.
Key points
- Register services near application startup.
- Keep business logic independent of the container where possible.
Example
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<OrderService>();
builder.Services.AddHttpClient<InventoryClient>();
var app = builder.Build();
app.MapGet("/health", () => Results.Ok(new { status = "ready" }));
app.Run();
What to expect
The app registers a scoped service and typed HTTP client before starting its request pipeline.
Practice exercise
Choose lifetimes for a service that stores request-specific state and explain why it should not be a singleton.
Key idea: Dependency injection is most useful when lifetimes and responsibilities are intentional.