Sunday, January 08, 2023

Choosing Between AddTransient, AddScoped and AddSingleton in ASP.NET Core

AddTransient & AddScoped are methods on the IServiceCollection interface which are used to register a service with a dependency injection container in your application.

When to use AddTransient:

  • It should be used when you want a new instance of a service to be created every time it is requested.
  • This lifetime is suitable for services that are lightweight and don't have any expensive resources or dependencies.
services.AddTransient<ILocalizationService, LocalizationService>();
  

Possible Scenarios:
A service that sends emails
A service that validates data
A service that calculates statistics

When to use AddScoped:

  • It should be used when you want a new instance of a service to be created once per HTTP request (for web apps) or service scope (for background services).
  • This lifetime is suitable for services that are expensive to create or have expensive resources or dependencies that should be shared within a single request or service scope.
 services.AddScoped<ICatalogvmRepository, CatalogvmRepository>();
  

Possible Scenarios:
A service that accesses a database
A service that calls a third-party API
A service that performs long-running tasks

When to use AddSingleTon:

Singleton lifetime services are created either:

  • The first time they're requested.
  • By the developer, when providing an implementation instance directly to the container. This approach is rarely needed.
services.AddSingleton<IServiceSettings, ServiceSettings>();
  

Every subsequent request of the service implementation from the dependency injection container uses the same instance. If the app requires singleton behavior, allow the service container to manage the service's lifetime. Don't implement the singleton design pattern and provide code to dispose of the singleton. Services should never be disposed by code that resolved the service from the container. If a type or factory is registered as a singleton, the container disposes the singleton automatically.

Register singleton services with AddSingleton. Singleton services must be thread safe and are often used in stateless services.

Tip:
It's a good idea to keep the lifetime of your services as short as possible, as this can help to reduce the memory usage of your application.  

No comments:

Post a Comment