C# Interview Question #94

What is the difference between Transient, Scoped, and Singleton lifetimes?

SOLID, DI, Testing & Practical C# Mid-Level Intermediate

Quick Interview Answer

ASP.NET Core's DI container supports several service lifetimes.

Detailed Explanation

ASP.NET Core's DI container supports several service lifetimes.

Transient creates a new service instance each time the service is requested.

Scoped creates one instance per dependency-injection scope. In a typical ASP.NET Core web application, this normally means one instance per HTTP request. EF Core DbContext is commonly registered as scoped.

Singleton creates one instance for the application's service-provider lifetime and shares it across requests.

A singleton must not directly depend on a scoped service because the lifetimes are incompatible. Singleton services also need careful thread-safety when they contain mutable state.

Code Example

builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddSingleton<ICacheService, CacheService>();