ASP.NET Core Interview Question #69
What is IServiceScope and why is it used?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
IServiceScope represents a dependency injection scope. Services registered as Scoped are shared within that scope and disposed when the scope is disposed.
Detailed Explanation
IServiceScope represents a dependency injection scope. Services registered as Scoped are shared within that scope and disposed when the scope is disposed.
ASP.NET Core automatically creates a scope for each normal HTTP request. Application code may need to create a scope manually outside request processing, for example during startup seeding or when a singleton/background component needs to execute scoped work.
A scope should always be disposed after use so disposable scoped services are cleaned up correctly.
Code Example
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider
.GetRequiredService<AppDbContext>();
await DatabaseSeeder.SeedAsync(db);