Dependency Injection life cycles: Singleton, Scoped, and Transient

Ercan Erdoğan
2 min readMar 5, 2024

--

Dependency injection is a technique that allows you to inject dependencies (such as classes or interfaces) into your classes, instead of creating them manually. This makes your code more loosely coupled, testable, and maintainable.

In ASP.NET Core, there are three types of dependency injection services: singleton, scoped, and transient. These types differ in how they are created and disposed by the dependency injection container.

  • A singleton service is created only once for the entire application and is shared by all the components that request it. This is useful for services that need to maintain a global state or provide a common functionality, such as logging, configuration, or caching.
  • A scoped service is created once per request (such as an HTTP request) and is disposed at the end of the request. This is useful for services that need to access request-specific data or resources, such as database context, user information, or configuration settings.
  • A transient service is created every time it is requested and is disposed as soon as it is no longer needed. This is useful for services that are lightweight and stateless, such as validators, mappers, or calculators.
image source : https://www.c-sharpcorner.com/article/service-lifetime-dependency-injection-asp-net-core/

You can register your services with the dependency injection container in the Startup class, using methods such as AddSingleton, AddScoped, or AddTransient. For example:

// Register a singleton service
services.AddSingleton<ILoggingService, LoggingService>();

// Register a scoped service
services.AddScoped<IDbContext, DbContext>();

// Register a transient service
services.AddTransient<IValidator, Validator>();

You can then inject your services into the constructors of your classes, like below:

public class OrderService
{
private readonly IValidator _validator;

public OrderService(IValidator validator)
{
_validator = validator;
}
}

Resources:

  1. https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines

--

--