Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET Singleton

Just want to make sure I am not assuming something foolish here, when implementing the singleton pattern in an ASP .Net web application the static variable scope is only for the current user session, right? If a second user is accessing the site it is a different memory scope...?

like image 426
Wesly Avatar asked Jan 25 '10 18:01

Wesly


People also ask

What is singleton in asp net?

Singleton is a design pattern, It means that there will be a single copy of your object inside server memory, which will be shared among all the requests (http/client). So, when you register any dependency in your application as a Singleton, then you will get a single copy of an object per server/node/instance.

What is a singleton service in C#?

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.

How does singleton work in NET Core?

The Singleton Design Pattern, as the name suggests, restricts the instantiation of a class to one object only. In other words, a class that follows the Singleton Design Pattern will not allow more than one instance of it to be created. The typical use cases of the Singleton Design Pattern are: LogManager.

What is the difference between transient and scoped and singleton?

Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.


1 Answers

Static members have a scope of the current worker process only, so it has nothing to do with users, because other requests aren't necessarily handled by the same worker process.

  • In order to share data with a specific user and across requests, use HttpContext.Current.Session.
  • In order to share data within a specific request, use HttpContext.Current.Items.
  • In order to share data across the entire application, either write a mechanism for that, or configure IIS to work with a single process and write a singleton / use Application.

By the way, the default number of worker processes is 1, so this is why the web is full of people thinking that static members have a scope of the entire application.

like image 157
Moshe Bixenshpaner Avatar answered Oct 29 '22 12:10

Moshe Bixenshpaner