ASP.NET Core Interview Question #55
What are Transient, Scoped, and Singleton service lifetimes?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
ASP.NET Core supports three primary DI lifetimes.
Detailed Explanation
ASP.NET Core supports three primary DI lifetimes.
Transient services are created each time they are requested. They are suitable for lightweight, stateless operations.
Scoped services are created once per dependency injection scope. In a typical web application, one scope is created for each HTTP request. Entity Framework Core DbContext is commonly scoped.
Singleton services are created once and reused for the application's lifetime. Singleton implementations must be thread-safe and should not directly depend on scoped services.
Code Example
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<ICacheService, CacheService>();