Session versus Singleton Pattern

I have a web application in which I would like to pull user settings from the database and save them for global access. Does it make sense to store data in a Singleton element or in a Session object? What is the difference between the two?

Is it better to store data as a reference to objects or break them into objects of type values ​​(ints and strings)?

+6
c # design-patterns asp.net-mvc
source share
5 answers

Session. What is this for. The session is stored in the global cache (mostly singleton), with the session identifier key. Thus, you only get data for the session of interest. Using singleton will basically replicate the global cache, and you will have to invent a mechanism to get data for each session independently.

Go ahead and store the object. Let the session worry about serializing it for something that can be restored. Be careful, however, with what you put on the Session. You do not want to store too much data there, or you will use a lot of memory (provided that the cache is in memory).

+11
source share

If these parameters will be used for all users of the site, put them in a singleton or in the application cache. If they are specific to each user, put them in a session.

Use object references when adding an application or session to the cache - I believe that value types will get a box so that they look like objects in the cache. If you use a singleton, it can go anyway.

+4
source share

A session object, definitely.

Singletones exist at the process level. This means that if you have 20 users who access your site at any time, they use the same singleton object. It's hard to get used to this concept if you are not involved in web development.

Sessions exist at the user level. This means that you can store data per user, not per process.

+2
source share

Sometimes I like the method below. It takes care of magic string issues and disables session variables. It also runs singleton at the session level, not at the application level.

public static SessionHandler GetInstance() { if (HttpContext.Current.Session["SessionHandler"] == null) { HttpContext.Current.Session["SessionHandler"] = new SessionHandler(); } return (SessionHandler)HttpContext.Current.Session["SessionHandler"]; } 

Then just use it like a regular singleton. Entering the necessary variables.

0
source share

This is taken from an old document, but it is still very relevant and works with pleasure ... I will post the link here, especially because it is an old link that may disappear. Taken from here.

Background

A Session object in ASP.Net can be used to store information specific to an individual site user. A session is indexed by a key name, and when used directly this way, it can lead to a large number of separate session names. An alternative approach is to instead create a singleton object to group related items and save this object with a given key name. "Singleton" is a general design pattern that indicates how to ensure that only one instance of a class exists at any time.

Benefits of Singleton Session Objects

  • Grouping Session Elements for Organization Purposes
  • Especially useful for a series of pages in transition, such as registering on a site. As soon as the process is completed, the object can be cleared from the session so that the memory can be restored (it is better to use server resources)
  • Analyzing the effect of changes on session information is much simpler.
  • Identify areas of the site that misuse the information (much clearer than just the name of the variable to determine if it is suitable for use)
  • Intellisense for property names and types after accessing an object

Disadvantages of Singleton Session Objects

It is more difficult to see the number of individual elements in a session ASP.Net trace results do not display values ​​inside an object Slow performance when using out-of-process session state (affects serialization)

Implementation

The first implementation step is to create a class file that represents a logical grouping of elements that should be stored together in one object. The following is an example class that demonstrates the technique:

 public class singleton { //Name that will be used as key for Session object private const string SESSION_SINGLETON = "SINGLETON"; //Variables to store the data (used to be individual // session key/value pairs) string lastName = ""; string firstName = ""; public string LastName { get { return lastName; } set { lastName = value; } } public string FirstName { get { return firstName; } set { firstName = value; } } //Private constructor so cannot create an instance // without using the correct method. This is // this is critical to properly implementing // as a singleton object, objects of this // class cannot be created from outside this // class private singleton() { } // Create as a static method so this can be called using // just the class name (no object instance is required). // It simplifies other code because it will always return // the single instance of this class, either newly created // or from the session public static singleton GetCurrentSingleton() { singleton oSingleton; if (null == System.Web.HttpContext.Current.Session[SESSION_SINGLETON]) { //No current session object exists, use private constructor to // create an instance, place it into the session oSingleton = new singleton(); System.Web.HttpContext.Current.Session[SESSION_SINGLETON] = oSingleton; } else { //Retrieve the already instance that was already created oSingleton = (singleton)System.Web.HttpContext.Current.Session[SESSION_SINGLETON]; } //Return the single instance of this class that was stored in the session return oSingleton; } } 

A page that wants to use this object simply does the following:

 singleton oSingleton = singleton.GetCurrentSingleton(); oSingleton.FirstName = "Robert"; oSingleton.LastName = "Boedigheimer"; 

Typically, this method will store many other variables in a given class or will be used for a series of web pages that execute a process. Another advantage of using this for a process on a website is that all the memory needed for session variables can be cleared by simply deleting the link to a singleton object. A class can implement a method that clients can use to clear the link; it can be called Dispose () to follow a typical .Net pattern when the class provides a way to clear:

 public static void Dispose() { //Cleanup this object so that GC can reclaim space System.Web.HttpContext.Current.Session.Remove(SESSION_SINGLETON); } 

Conclusion

There are many advantages to using singleton objects stored in a Session object instead of using separate session keys to store information. It is useful for objects that should exist for the entire session (grouping of logical elements, impact analysis, intellisense, etc.) and especially for objects that are really needed only for a certain period of time on the website until the user completes a specific process (it is much easier to identify the misuse of variables and save resources when the process ends, but the session will continue).

0
source share

All Articles