Scoped
DbContext — one instance per HTTP request.
When to use: services that share state within a single request,
such as
DbContext and unit-of-work patterns.
Where do the three IDs come from?
When this page loads, ASP.NET Core builds the page model by calling its constructor.
The container resolves IAppDbContext twice in the page, and also injects
SampleService. Because this service is scoped, SampleService receives the same instance as the page — one object shared for this HTTP request only.
Page constructor — ScopedModel
public ScopedModel( IAppDbContext firstInjection, // parameter 1: first injection IAppDbContext secondInjection, // parameter 2: second injection SampleService sampleService) // parameter 3: via SampleService { FirstInjectionId = firstInjection.InstanceId; SecondInjectionId = secondInjection.InstanceId; SampleServiceId = sampleService.AppDbContext.InstanceId; }
SampleService constructor
public SampleService( IAppDbContext appDbContext, ...) { AppDbContext = appDbContext; } // This page reads: sampleService.AppDbContext.InstanceId
Result in this request
| Resolution | Constructor parameter | Instance ID |
|---|---|---|
| First injection | firstInjection |
3c7e77c2-12aa-4ee8-9b4a-10e0fd1edc2d |
| Second injection | secondInjection |
3c7e77c2-12aa-4ee8-9b4a-10e0fd1edc2d |
Via SampleService |
sampleService.AppDbContext |
3c7e77c2-12aa-4ee8-9b4a-10e0fd1edc2d |
All IDs match within this request. Refresh the page to simulate a new request —
you will get a new ID, but all resolutions in that request still share it.
Registration in Program.cs:
builder.Services.AddScoped<IAppDbContext, AppDbContext>();