SOLID & Design Patterns Interview Question #142
What is a Scoped service in ASP.NET Core and when is it appropriate?
Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced
Quick Interview Answer
A scoped service has one instance per dependency-injection scope. In an ASP.NET Core web application, a request normally creates one scope, so scoped services are commonly used for request-oriented work and EF Core DbContext instances.
Detailed Explanation
A scoped service has one instance per dependency-injection scope. In an ASP.NET Core web application, a request normally creates one scope, so scoped services are commonly used for request-oriented work and EF Core DbContext instances.
Scoped services can depend on other scoped or singleton services. Injecting a scoped service directly into a singleton creates a lifetime mismatch and should be avoided.
Code Example
builder.Services.AddScoped<AppDbContext>();
builder.Services.AddScoped<IOrderRepository,
OrderRepository>();
// Same request -> same scoped instance
// unless additional scopes are created.