Tutorial :Provide strongly typed access to the session object


What is the best way to provide strongly typed access to the session object? I am planning on turning on Option Strict, which is causing the compiler to complain about my lazy programming technique of directly accessing the session object:

Dim blah As Integer = Session("Blah")  

My initial thought is to create a class that wraps the session and provides strongly typed properties for the information stored in the session. However, I cannot decide if the class should be a singleton, or instantiated on every use, or where the code should reside (i.e. within the web project or within a class library).

I'm leaning towards a singleton in my class library, but I don't know if that is the best solution, or if I am missing any other possibilities.

Proposed Solution:

Public Class SessionAccess      Public Shared Property Blah(ByVal session As HttpSessionState) As Integer          Get              Return Convert.ToInt32(session("Blah"))          End Get          Set(ByVal value As Integer)              session("Blah") = value          End Set      End Property  End Class  

Code Behind:

Dim blah As Integer = SessionAccess.Blah(session)  


I deleted my original answer as @Jason Berkan made a very good point when he questioned my answer. Jason, I think this idea is fine.

The only thing I would change in your code example is to check to ensure that the session variable exists.


Either my proposal is the "standard" way to do it, or else no one wraps their session access, since this question hasn't received very many answers.

I did find one line in this answer that mentioned creating a SessionManager:

  • Wrap the ASP.NET Session with a SessionManager to avoid development mistakes in spelling, etc. when referencing items from Session.

I have not thought of any reason to not use a singleton class to provide typed access to the session, so that is the solution I went with in the project.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »