liveBook · Manning

IServiceScope

As explained in ASP.NET Core in Action, 3e

IServiceScope is the .NET abstraction representing a dependency-injection scope and providing access to the scoped service provider.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains scope creation, ServiceProvider access, lifetime behavior, and disposal, but does not detail the interface implementation.
Examples
Demonstrates resolving DataContext in Program.cs with AddScoped, CreateAsyncScope, GetRequiredService, and await using.
What it assumes
Assumes familiarity with dependency-injection registration and service lifetimes while teaching manual scope creation from Program.cs.
What you can do after
Operate/configure dependency injection by creating, using, and disposing a scope around manually resolved services.
How it connects
Connects dependency injection, IServiceProvider, scoped services, transient services, singleton services, and HTTP request scopes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.