ASP.NET Core Interview Question #12

What are Transient, Scoped, and Singleton service lifetimes?

ASP.NET Core Fundamentals Junior Beginner

Quick Interview Answer

Transient services are created each time they are requested. They are suitable for lightweight, stateless services.

Detailed Explanation

Transient services are created each time they are requested. They are suitable for lightweight, stateless services.

Scoped services are created once per request scope in a typical web application. Entity Framework Core DbContext is commonly registered as scoped.

Singleton services are created once and reused for the application's lifetime. Singleton implementations must be thread-safe and must not directly depend on scoped services because the lifetimes are incompatible.

Code Example

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