IServiceScope represents one dependency-injection scope. Its ServiceProvider property lets you resolve scoped and transient services, which are disposed when the scope is disposed. section 9.5 section 9.6
ASP.NET Core creates a scope for each HTTP request. Outside a request—such as in Program.cs—create a scope manually instead of resolving scoped or transient services directly from WebApplication.Services. section 9.5 section 9.6
Resolve a scoped service in Program.cs
Register DataContext with AddScoped, build the application, and create an asynchronous scope with app.Services.CreateAsyncScope(). Resolve DataContext through scope.ServiceProvider.GetRequiredService<DataContext>(). The await using block disposes the scope and its resolved services before app.Run(). Prefer CreateAsyncScope when possible; it addresses asynchronous disposal scenarios and was introduced in .NET 6. section 9.5 section 9.6
Listing 9.14 Resolving a scoped service using IServiceScope in Program.cs
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<DataContext>(); #1
WebApplication app = builder.Build();
await using (var scope = app.Services.CreateAsyncScope()) #2
{
var dbContext = #3
scope.ServiceProvider.GetRequiredService<DataContext>(); #3
Console.WriteLine($"Retrieved scope: {dbContext.RowCount}");
} #4
app.Run();
Runnable Program.cs pattern showing registration, asynchronous scope creation, scoped-service resolution, and automatic disposal. section 9.5
