views:

36

answers:

2

I've got an ASP.Net project that uses session state, I'd like to be a little more strict about how we access session state, I'm not happy about all the strings floating around the code. I also need to know when a particular value is stored/updated in session state for tracking that object's latest value.

The string issue is easy to solve using constants, but it doesn't help with the tracking. Encapsulating them all in a single class is appealing, but then I have to pass the session object to that class, and that seems a little messy

I'm thinking of using one of two options:

  1. Extension getters and setters on the session object
  2. An extension method on the session object to return a class with the getters and setters

The first gives me the syntax:

var thing = Session.GetThing();
Session.SetThing(thing);

The second gives:

var thing = Session.Wrapper().Thing;
Session.Wrapper().Thing = thing;

Both have their appeal, though I'm leaning towards the second. In an ideal world I'd like to be able to do this:

var thing = Session.Thing(); // easy to do
Session.Thing() = thing; // don't think it's possible

What's the preferred way of handling this? Any of these, another way, or am I just doing it wrong?

+3  A: 

You don't have to pass the Session to each class, you can have:

public class State
{
    public string Something
    {
        get { return HttpContext.Current.Session["Something"] as string; }
        set { HttpContext.Current.Session["Something"] = value; }
    }
}

This, I believe, is the typical approach. HttpContext has the Current property which is statically available.

Noon Silk
Thanks, I was over thinking it. I should have looked for how to access the session state from elsewhere rather than trying to extend the HttpSessionState object.
baralong
A: 

My preferred method is to put all of the variables that need access into an object. Then I put a variable in our page's base class that provides the appropriate access to the object in the session. The only manner of true enforcement of this is to provide a standard that requires usage of this object and then code/peer review to ensure that miscellaneous strings/variables don't end up clogging the session up.

Joel Etherton
not quite what I was after as I have some places I need to access this from controls and sometimes from web services
baralong
@baralong - Actually our framework takes all of that into account. From any control in the architecture you can get to the session object through our properties and methods specifically for that purpose. I'd say it's really all down to how you plan everything.
Joel Etherton