1

I am trying to understand the singleton lifetime in the context of DI in ASP.NET Core.

First, from what I can see a Singleton instance will be available "across application lifetime." But what does "application lifetime" mean? If it's a website and if a user logs in, singleton created first and user logs out and comes back in to the site after a few hours and logs back in will that user gets the same singleton instance? what about multiple users? Can multiple users get the same singleton instance?

Second, When does application lifetime end in .NET Core? Most articles talk about registering for application shutdown events. But what triggers an application shutdown? Is it always external events like IISreset or a system shutdown? Or internal events like memory crash etc? If no resets or memory or any other issues, will it keep going forever?

Steven
  • 166,672
  • 24
  • 332
  • 435
Dotnet Dev
  • 25
  • 4
  • Here you have the microsoft docs, essentially a Singleton service is instantiated only once when the app "starts", and that single instance is the one being used everywhere. It has nothing to do with users. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-lifetimes – devcrp May 17 '20 at 19:49

1 Answers1

2

Singleton here (i.e. not the singleton design pattern) means a single instance for the created root IServiceProvider, so effectively a single instance will be used for all requests, until the process exits.

It has nothing to do with per request or session. If you want a new instance per request, but shared, use the scoped lifetime.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 3
    An important distinction between the Singleton Design Pattern and the Singleton Lifestyle is that with the Singleton Design pattern there will be at most 1 instance for the complete app domain. With the Singleton lifestyle, however, if you create multiple DI Container instances (so multiple "root `IServiceProvider" instances, as Daniel notes), there will be at most one instance *per provider*. – Steven May 17 '20 at 19:46