ASP.NET Core MVC Interview Question #127
What are Transient, Scoped, and Singleton service lifetimes?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
Transient services are created each time they are requested. Scoped services are created once per dependency-injection scope; in a typical MVC HTTP request, that means one instance per request. Singleton services use one instance for the application's service-provider lifetime.
Detailed Explanation
Transient services are created each time they are requested. Scoped services are created once per dependency-injection scope; in a typical MVC HTTP request, that means one instance per request. Singleton services use one instance for the application's service-provider lifetime.
The lifetime must match the service's state and dependencies. A singleton must not directly capture a scoped dependency because the scoped service could outlive its intended request scope.
Code Example
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddSingleton<IClock, SystemClock>();