← Foundations path
.NETFoundations 23 / 37

Scope and the root provider

“What is a scope in ASP.NET Core dependency injection, and what is the root provider?”

The root lives as long as the app. A scope lives for one request, and so do the scoped objects inside it.

See it

root provider · lives as long as the appIndiaRulesInMemory repoTimeProviderLoanService · lives till app stopsscope · request Ascope · request Brequest ALoansControllerLoanService #12nd ask → same #1request BLoansControllerLoanService #2
1 / 11At startup Build() makes the root provider. It lives until the app stops and keeps the .

In plain words

The root provider is the 's top level: made once when the app starts, alive until it stops. A scope is a short-lived group of objects. ASP.NET Core opens one for each web request. A scoped service such as is made once inside that group, shared by everything in that request, and let go when the request ends. Two requests at the same time get two scopes and two objects. The root keeps the singletons: one object each, shared by every request.

Say it in the interview

In the lending API

Program.cs makes the root, the controller runs inside a request's scope, and a test proves both. Press Next line to walk through them.

Lending.sln · where these 3 files sit
  • src/Api/
    • Controllers/Servicing/
  • tests/Api.IntegrationTests/
Diagram · step 1At startup Build() makes the root provider. It lives until the app stops and keeps the .
root provider · lives as long as the appIndiaRulesInMemory repoTimeProviderLoanService · lives till app stopsscope · request Ascope · request Brequest ALoansControllerLoanService #12nd ask → same #1request BLoansControllerLoanService #2
Program.cs · line 15 · 1 of 4Singleton: built once and kept by the root provider. How these lines work is on the page.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

With AI tools

A worked answer from this app's research, not a quote: Copilot suggested making a singleton to fix an . The candidate rejected it, because is scoped by default and not thread-safe, so never a singleton. The real bug was a background job holding on to a scoped service; the fix was a scope from , plus a test like the one above.

Read more: Microsoft Learn: service lifetimes and scope validation · Microsoft Learn: DI in ASP.NET Core · Microsoft Learn: scoped services in a background service · Microsoft Learn: integration tests with WebApplicationFactory