This post was originally going to be a comment on Jarret@Work's blog post about "Using Extension Methods for Session Values", but I decided to make a full blog post out of it. Jarret employed extension methods such Bar()/SetBar() and Foo()/SetFoo() to have strongly-typed session data. While his method certainly works, I've taken a different approach that I think is a bit more flexible and reads better.
Like Jarret, I maintain a "SessionKeys" class – there is no easier way to ask for trouble than using a magic string buried across 4 or 5 web pages. But I expose my session data in a base class that all controllers in my application derive from. Here's a sample from my post on unit testing ASP.NET MVC controllers:
Now all of my controllers inherit from BaseController and they can easily access the data stored in the Session by utilizing the SpeakerInfo property. I like this over Jarret's implementation for two reasons:
- Properties make the code more readable than get/set methods (in my opinion).
- I can change where/how SpeakerInfo is stored without affecting the rest of my code (perhaps to use a database instead of Session).
To be fair, #2 is also possible with Jarret's implementation. He can change the code in his get/set methods. But his code would still read "Session.Bar()" and "Session.SetBar()" when (if the implementation was changed to use a database), it wouldn't really be using the Session.