Strongly Typed .NET Session Pattern

When working in a strongly typed language like C#, I prefer to avoid being “stringly typed“. Thus I typically wrap .NET’s session object with a custom wrapper. This offers three core benefits:

  1. Compile-time error checking to protect from typos and assigning improper types
  2. Find all references support makes it easy to see all uses of a given session value. This aids refactoring and helps protect from accidentally placing the same data in multiple session variables.
  3. Intellisense support in the IDE saves typing and avoids hunting around for the desired magic string.

Here’s a quick example implementation that wraps two session values.

This example is simple for readability, but it would be wise to add a check in the UserID setter to assure an integer is being passed. This would assure only appropriate types can be stored in a given session variable.

Accessing a UserName from session is safe and simple:

Of course, if you’re using dependency injection, then the statics should be replaced with instance variables and an interface should be defined to support mocking.

Subscribe to Email Updates (No spam. Just new posts.)

One thought on “Strongly Typed .NET Session Pattern