in Personal

Strongly-typed Session Objects

Until this summer, I didn’t see anything wrong with putting something in the Session object by saying:
 
Session[“Something”] = MyVar;

Of course, that’s a perfectly legal way to use the Session object and it works quite well.  So what’s the problem?

Well, let me give you an example of why this can be bad.  On one of the big projects I’m working on this summer, we use the Session object to store GUID values which are the keys to tons of things in the system (e.g. you use this GUID to look things up in about 20 different tables).  What we’re building is basically a massive ASP.NET-based wizard for doing some business tasks.  So it’s quite critical that this GUID is passed between pages in a way that each of them can understand.  Well, the situation has now come up that some people started putting the GUID in Session[“GUID”] (which is right) but as a string instead of a GUID object.  I, on the other hand, am storing my GUIDs in the same Session location, but I’m storing the real GUID object. 

Because you can’t cast a string into a Guid, we have to have two sets of code to convert Session[“GUID”] back into a Guid.  Now you can solve this problem by having standards and enforcing them, but that still leaves room for people to make mistakes and still get it wrong.  After having to deal with this issue for a couple of days (we’re still trying to find every place that sets these Guids so they can be standardized), I am really thinking making a wrapper for your Session objects would be a good idea.  Using the wrapper idea on the project I’m currenting working on, I would have a property of type Guid that will still set and get the Session[“GUID”] object, but it will be the only way to get a Guid in or out of the session…this way, it doesn’t matter if it’s stored as a Guid or string – you’re code never knows.  And you don’t have the problem of people storing the same thing in multiple places (or at least it would help with that). 

I know this is all fairly obvious stuff, but wrappers (for stuff like this) and all the people wanting strongly-typed collections didn’t really make a lot of sense to me until this summer.  Of course, I saw the benefit it added, but I didn’t realize why that was so important, but I certainly know now and in the future, my code is going to look quite different.