Dependency injection and service lifetimes
The idea
ASP.NET Core has a built-in Inversion of Control (IoC) container with robust support for Dependency Injection (DI). DI is a design pattern that allows loose coupling between software components. The dependencies are provided (injected) into objects, rather than the objects creating their own dependencies.
Registering services
Services (dependencies) are registered with the DI container in Program.cs, or in the ConfigureServices method of Startup.cs in older templates. You register them using methods on IServiceCollection.
Service lifetimes
AddSingleton(): a single instance of the service is created for the entire application lifetime. That instance is shared across all requests.AddScoped(): a new instance of the service is created once per client request, or per scope. Within the same request, the same instance is reused.AddTransient(): a new instance of the service is created every time it is requested from the DI container.
Understanding these lifetimes is crucial for application correctness and performance.
A common pitfall
A common pitfall is injecting a Scoped service into a Singleton service, for example an EF Core DbContext (see the DbContext noteORMs, DbContext and entitiesWhat EF Core is, and the four ideas its API is built on.Opens in a new tab). The Scoped service then behaves like a Singleton for the lifetime of the outer Singleton. That causes problems such as data from one request inadvertently affecting another, or trouble with DbContext change tracking across requests.
IServiceProvider
IServiceProvider is the interface the application uses to resolve registered services from the DI container. Services are typically resolved implicitly through constructor injection. You can inject IServiceProvider directly if you need to resolve services manually, for example through HttpContext.RequestServices.
How these lifetimes relate to threads and processes is in DI scopes, threads and processesDI scopes, threads and processesA scope is a logical unit of work, not a thread or a process.Opens in a new tab.
Sources
- 100+ .NET Core Interview Questions and Answers (2025), WeCP · accessed May 16, 2025