Asp.net core - What is the difference between AddTransient, AddSingleton and AddScoped?

When you wish to use dependency injection in Asp.net core you have three choices for the lifetime scope of your dependency. The three choices are AddTransient, AddScoped and AddSingleton - they decide the lifetime of your dependency:

  • AddTransient: You get a new instance of the dependency every time it is injected as a dependency in a controller or service.
  • AddScoped: You get a new instance of the dependency for every request made, but it will be the same within the lifetime of the request.
  • AddSingleton: You will always get the same instance of the object and it is only created once.

So the above is simple to understand on the surface, but what does this really mean and when should you use what?

  • AddTransient: If your objects are costly to instantiate you should not use transient as lifetime. Often our objects have little to no state and there is no reason not to use Transient except for a small memory overhead of creating a new object.
  • AddScoped: Is a good choice if you need to cache items within the same request.
  • AddSingleton: Is used for instances that can be shared across the application. It is ideal for caching or to be used for objects that are costly to instantiate. Be careful not to accidentally make singletons of services that has state which should not be shared, especially if it is sensitive user data. With everything that lives as long as the application, it can create memory leaks which need to be contained.

Keep in mind that if you inject Transient or Scoped objects into Singletons or Transient into scoped, they will "inherit" their lifetime. They will not be disposed until the object that has them as a dependency is.

That is it

Microsoft has an excellent tutorial of the above found here.

I hope you enjoyed this post on the different lifetimes you can set for services in asp.net core, let me know in the comments below if you did!