ASP.NET Core Web API Interview Question #102

What are Transient, Scoped, and Singleton service lifetimes?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

Transient services are created each time they are requested. Scoped services are created once per dependency-injection scope; in a typical HTTP request, that means one instance per request. Singleton services use one instance for the application's lifetime.

Detailed Explanation

Transient services are created each time they are requested. Scoped services are created once per dependency-injection scope; in a typical HTTP request, that means one instance per request. Singleton services use one instance for the application's lifetime.

The lifetime must match the service's state and dependencies. A singleton should not directly depend on a scoped service such as a normal request-scoped DbContext.

Code Example

builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<ISystemClock, SystemClock>();