views:

42

answers:

2

I want to initiate a class for each user at the start of the user's session so that a single class can be used throughout the user's session. I checked out this post but I'm not sure where I should be placing this Sessionhandler class. Inside global.asax? How do I go about accomplishing this?

+1  A: 

The class itself can go anywhere, since it is static, you just need to make sure you have a using directive for the right namespace when your accessing it.

If you want to create an instance of some class and store it in the user's session (perhaps using this SessionHandler class), then you can do that work in the Session_OnStart() handler in Global.asax.cs:

protected void Session_OnStart()
{
    // Do your work here
}
ckramer
It looks like I asked my question incorrectly. I'm looking to instantiate a non-static class. Basically I wan't to have a class called for each user so I can run some methods or store class properties during the length of the user's session.For example I would call a timer function at the beginning of the user's session that would run until the user's session ends. Does that make sense?
James Santiago
+2  A: 

Hi James ,

I take that you will be running a common piece of code for all authenticated users (may be timers as you have mentioned).

Please see if the following steps solves your problem.

1. Have the user initialisation code in Session_OnStart

E.g.,

protected void Session_OnStart()
{
    // Do user initialization here
    Session["useridentifier"] = id;
    Session["isAuthenticated"] = true;
}

2. Derive a BaseController from Controller class , so that all the other controllers that you develop shall inherit from BaseController (de coupling)

E.g.,

Public class BaseController : Controller
{
}

3. Have the Common methods that needs to be executed in the constructor

E.g.,

Public class BaseController : Controller
{
   public BaseController()
   {
     if((bool.Parse(Session["isAuthenticated"]))
     {
       // write the user specific code here.
     }
  }

Hope this helps.

Thanks , Vijay

vijaysylvester
I tried it out and it seems to be doing the trick. Thanks
James Santiago