Vault of Thoughts


Please visit my new blog at

Strongly typed Session object

When developing stateless applications sooner or later there comes a time, when you need to store some information between requests. In technologies such as PHP and ASP.NET there is a special object to serve this function. It is called the Session object in ASP.NET. Using it is very easy, just use an indexer in a form of a string to set and retrieve some information that you want to persist between requests. Now the main problem with such an approach is the fact that it is hard to control. As an example: suppose that there are two pages using the Session object to store some state and make it accessible to each other. The simplies approach is to just use the Session object on one page to store an object and on the other to retrieve it:

Session["SomeKey"] = "some value";

object value = Session["SomeKey"];

Suppose further that there are many pages that access the value with "SomeKey" key. Sooner or later (sooner) you will lose a track of where and what is setting and retrieving this value. More over, it is hard to change since it requires you to look through multiple files - a very error prone technique.

Another solution would be to use some kind of public constant variable in place of the "SomeKey". It is better but not perfect.

A more secure solution would be to create a strongly typed class for accessing the Session object by means of properties. This way you only have to change session related stuff in one place and every braking change is detected at the compile time. Additionaly, when working with other developers, they do not have to ask you, what kind of object is available through the Session[“SomeKey”].

As a side note I would strongly encourage you to avoid Session object whenever you can. It is a hell to work with a statefull statless application :-(

kick it on

If you liked this article why not support its author by making a donation?


Post a Comment

Links to this post:

Create a Link

<< Home