Differences Between Scoped, Transient, And Singleton Service

Introduction

In this article, we will see the difference between AddScoped vs AddTransient vs AddSingleton in .net core.

Why we require

  • It defines the lifetime of object creation or a registration in the .net core with the help of Dependency Injection.
  • The DI Container has to decide whether to return a new object of the service or consume an existing instance.
  • The lifetime of the Service depends on how we instantiate the dependency.
  • We define the lifetime when we register the service.

Three types of lifetime and registration options

  1. Scoped
  2. Transient
  3. Singleton

Scoped

  • In this service, with every HTTP request, we get a new instance.
  • The same instance is provided for the entire scope of that request.
    • eg., if we have a couple of parameter in the controller, both object contains the same instance across the request
  • This is a better option when you want to maintain a state within a request.
services.AddScoped<IAuthService,AuthService>();

Transient

  • A new service instance is created for each object in the HTTP request.
  • This is a good approach for the multithreading approach because both objects are independent of one another.
  • The instance is created every time they will use more memory and resources and can have a negative impact on performance
  • Utilize for the lightweight service with little or no state.
services.AddTransient<ICronJobService,CronJobService>();

Singleton

  • Only one service instance was created throughout the lifetime.
  • Reused the same instance in future, wherever the service is required
  • Since it's a single lifetime service creation, memory leaks in these services will build up over time.
  • Also, it has memory efficient as they are created once reused everywhere.
services.AddSingleton<ILoggingService, LoggingService>();

When to use which Service

Singleton approach => We can use this for logging service, feature flag(to on and off module while deployment), and email service

Scoped approach => This is a better option when you want to maintain a state within a request.

Transient approach =>  Use this approach for the lightweight service with little or no state.

What do you think?

I hope you enjoyed this article. I would like to have feedback from my readers.

Your valuable feedback, questions, or comments about this article are always welcome.


Similar Articles