3

i'm building a web application with asp.net c# and i have a class that i want to use in multiple pages witouth instantiate it every time. I need to load the data in it and never lose them during the user session time. I thought about the singleton-pattern but it shared the instance of the class beetween browsers. How can i solve the problem?

Stefano
  • 3,213
  • 9
  • 60
  • 101

3 Answers3

9

Singleton is not the answer. Look at Session State, ViewState and Cookies.

Chuck Conway
  • 16,287
  • 11
  • 58
  • 101
  • 1
    Singleton *might* be the answer if he needs to gaurantee that reentrant calls only generate a single use of the class/object. That wouldnt be strictly needed unless the OP was using threading or some other method of running concurrent code for a single user session – GrayWizardx Sep 16 '10 at 16:35
  • i must have only one instance of the class for each user that open the page. My problem is that with singleton pattern and static instance i share the data beetween users and so browsers – Stefano Sep 16 '10 at 16:52
  • 1
    @Stefano If you use a session you can achieve what you want. Only one instance of the data across pages and for the life of the session. However, this will fail if the same user logs in from a different computer or different browser. – Chuck Conway Sep 16 '10 at 19:06
1
UserData data = new UserData(somedata);

Session["UserData"] = data;

next page

UserData data = (UserData) Session["UserData"];
Rohrbs
  • 1,855
  • 13
  • 11
1

If you have inproc session state you can use something like this

class Singleton
{
    static object locker = new Object();

    public static Singleton Instance
    {
        get
        {
            var inst = HttpContext.Current.Session["InstanceKey"] as Singleton;
            if (inst == null)
            {
                lock (locker)
                {
                    inst = HttpContext.Current.Session["InstanceKey"] as Singleton;
                    if (inst == null)
                    {
                        inst = new Singleton();
                        HttpContext.Current.Session["InstanceKey"] = inst;
                    }
                }
            }
            return inst;
        }
    }
}

Code can be improved, to avoid locking for all users. Don't know if this is a good idea to implement Singleton like that, I'd recommend you to see if you can design your code in other way.

Insomniac
  • 3,354
  • 2
  • 23
  • 24