ASP.NET Core Interview Question #57
When should you use a Scoped service?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
A Scoped service is appropriate when one instance should be shared within a single request or logical operation but not across unrelated requests.
Detailed Explanation
A Scoped service is appropriate when one instance should be shared within a single request or logical operation but not across unrelated requests.
Repositories and business services that work with an Entity Framework Core DbContext are commonly scoped because the DbContext itself is normally scoped. This allows related operations during one request to participate in the same unit of work.
Scoped services should not be captured directly by singleton services because doing so can effectively extend the scoped object's lifetime and cause incorrect behavior.
Code Example
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();