Thursday, May 30, 2013

Wrap your session

Okay, I have worked on a fair number of old and badly built web sites. Often they will use session. Session seems really great. You can just magically add state to your stateless protocol! But once you start using it you find that is actually becomes a massive headache and while it is a useful technique it is also probably the easiest way to write shitty and buggy web code. So I would advise not using session, but since many systems already use session I wanted to talk about a pattern that can easily be added to your code that will make your session code use much easier to handle. Code included below with a single example property.


public interface ISession
{
string PageStateStarted { get; set; }
}
public class SessionWrapper : ISession
{
private HttpSessionState sessionState;
internal SessionWrapper(HttpSessionState session)
{
sessionState = session;
}
public string PageStateStarted
{
get { return (string) sessionState["PageStateStarted"]; }
set { sessionState["PageStateStarted"] = value; }
}
}

public class SessionManager
{
private static ISession _session;
public static ISession Session
{
get
{
return _session ?? (_session = new SessionWrapper(HttpContext.Current.Session));
}
}
public static void InjectSessionStub(ISession session)
{
_session = session;
}
public static void RestoreDefaults()
{
_session = null;
}
}

So why should you do this? For several reasons, one is that you add typing information. Now some people don't have a lot of respect for typing and like dynamic stuff, but adding types to your session variables will make your code easier to understand. It also allows static analysis by tools like resharper. You can find every place where a session variable is modified very easily using this pattern. And the last benefit you could probably guess based on my inclusion of "InjectSessionStub". This patterns allows you to unit test session code. This pattern is also easy to put into your code and easy to refactor into your code where you are using session.

No comments:

Post a Comment