Wednesday, July 8, 2009

Managing Session State – Using A Strongly Typed Session Store

Download the example VS 2008 solution here.

As an ASP.NET developer, I’ve found myself in situations where I’ve needed to manage state for the current use by using Session.  I know that there are other ways to keep track of a user’s state aside from Session, and that the use of Session should be very used with discretion. The point of this post is not to say that any time you need to keep track of state in your web application that you should use Session, but rather to present one way of effectively managing this if you ever find that Session is something that you want or need to use.

In my experience, I’ve seen many issues with developers using Session ineffectively and dangerously.  Here are some common follies of using (or misusing) Session:  assuming that something is in Session when it may or may not be, mistyping of the string literal when placing something in or retrieving it from Session (e.g. Session[“UserId”] and Session[“UserID”] are not referencing the same thing), and accidentally having the same Session variable mean two different things.

I created a pattern in the form of a SessionRepository class that will hopefully alleviate some of these issues that are commonly found throughout ASP.NET projects.

This is an example SessionRepository property:


This is an example snippet of code that you write while using the SessionRepository:


This gives us a uniform way of setting and getting things from the session without as much work that has to be done with casting and null checking.  It also gives uniform way of removing from the session.  We also are able to easily find all references to a given session variable without having to search our entire solution for strings.  We can just right click on the property and click ‘Find All References,’ and we’re done.

I’ve included a link to an example VS 2008 Web Application project that uses this pattern.  Refer to the SessionState folder within the project.  Hopefully this will prevent some of the head banging that I’ve experienced while working with Session.  Happy Coding!


Download it here.

No comments: