Singleton, Scoped, and Transient Services. What are the differences?

In .NET's dependency injection there are three major lifetimes: Singleton, Scoped, and Transient. They are initiated with AddSingleton, AddScoped, and AddTransient respectively.

// Singleton

builder.Services.AddSingleton<ICookies, Cookies>();

// Scoped

builder.Services.AddScoped<ICache, Cache>();

// Transient

builder.Services.AddTransient<ILookup, Lookup>();

Singleton creates a single instance once and reuses the same object in all calls. Use Singletons where you need to maintain application wide state, for example, application configuration, logging service, caching of data, etc.

  • Singletons are memory efficient as they are created once and reused everywhere.
  • Memory leaks in these services will build up over time.

Scoped lifetime services are created once per request. For example, in MVC it creates one instance for each HTTP request, but it uses the same instance in the other calls within the same web request.

  • Scoped is a good option when you want to maintain state within a request.

Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services. Since they are created every time, they will use more memory & resources and can have negative impact on performance.

  • Transient is good for lightweight services with little or no state.

Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023

Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.