views:

99

answers:

3

I am working with ASP.net 3.5 MVC application.

I have one assembly which has ClassA. I have another assembly which creates the object of ClassA

Now the question is , how to Intialize the object as a static only for one session. The object will be static across the session. New Instance of the object should be created only when new session starts. In addition, for the previous session the object should be available with the previous intsance.

How to do this ?

A: 

You could use the Session_Start event in global.asax and put the instance of ClassA in the session. You could then just read it from the session and it will be the same instance for the same user as long as the session is alive.

Darin Dimitrov
+1  A: 

Wrap the object into a Singleton class. Singleton class should cache the object into Session. Perform lazy-load to create the object only when accessed for the first time and then cache into session. This will also work even in case when the session expires.

http://en.wikipedia.org/wiki/Singleton%5Fpattern

http://www.dofactory.com/patterns/PatternSingleton.aspx

this. __curious_geek
+1  A: 

You can use HTTPModule (hit every time) which checks the Application Object with some key (unique for a session, probably you can use SessionId + something within the key). This we are doing to access previous session's object , in case we don't want this, then we can set with some key not unique to a particular session.

Now as the module is hit, and we find no object in Application Object for the particular session we will create the object and will set in this HTTPModule Class as static.

Then the following code might help in case we find no object in HTTPApplication object for the current session(in case we dont need previous session's object then we can use HTTPSession object also to check for ClassA object's availability, even a flag with in HTTPSession will suffice, no need to save any object in HTTPSession, module class will give that).

In HTTPModule class the following should be added: Static variable which can be accessed from this HTTPModule class by any other class of your application.

/* HTTP Module Class */
public class SomeModuleClass
{
    public static ClassA classA = null;

    private void someFunctionOfModuleFiringEverytime()
    {  
       /* if there is no instance of ClassA in HTTPApplication or HTTPSession object*/

        SessionManager sessionManager = new SessionManager();
        /* one object of SessionManager gives back one object of ClassA always*/
        classA = sessionManager.getClassA();
    }
}


/* an assembly which is making the Class A instance*/
public class SessionManager
{
    private ClassA classInstance=null;

    public ClassA getClassA()
    {
        if (classInstance == null)
            classInstance = new ClassA();

            return classInstance;
    }
}

/* class from another assembly*/
public class ClassA
{
    public ClassA()
    {

    }
}
Beginner