Blog archive
RSS

Blog

ASP.NET Core has three lifetimes of Singleton, Scoped, and Transient

Question #1
“ASP.NET Core has dependency injection to manage services; are you aware of the different lifetimes? What are they, and what does each mean?”

ASP.NET Core has three lifetimes of Singleton, Scoped, and Transient.

ASP.NET Core services container will create services registered as a singleton only once for the duration of the application’s lifetime. Singletons are helpful for expensive services or services with little to no internal state.

As the name suggests, with regard to scoped services, they are created within a scope. The scope is typically the lifetime of an HTTP request, but not necessarily always. I, as a developer, might create custom scopes in code, but anyone should be careful to use this technique sparingly.

Finally, ASP.NET Core creates transient services when a dependent instance asks for them. I might consider registering dependencies as transient as the “safest” approach to creating dependencies as there’s no chance for contention, race conditions, or deadlocks. Still, it can also come at the expense of performance and resource utilization.

Each lifetime has its use, and it depends on the dependency we are registering.