How to create a C# session object wrapper?
asp.net, c#, class-library, iis, session
Solution
Normally I just have a static class that wraps my session data and makes it type safe like:
public static class MySessionHelper
{
public static string CustomItem1
{
get { return HttpContext.Current.Session["CustomItem1"] as string; }
set { HttpContext.Current.Session["CustomItem1"] = value; }
}
public static int CustomItem2
{
get { return (int)(HttpContext.Current.Session["CustomItem2"]); }
set { HttpContext.Current.Session["CustomItem2"] = value; }
}
// etc...
}
Then when I need to get or set an item you would just do the following:
// Set
MySessionHelper.CustomItem1 = "Hello";
// Get
string test = MySessionHelper.CustomItem1;
Is this what you were looking for?
EDIT: As per my comment on your question, you shouldn't access the session directly from pages within your application. A wrapper class will make not only make the access type safe but will also give you a central point to make all changes. With your application using the wrapper, you can easily swap out Session for a datastore of your choice at any point without making changes to every single page that uses the session.
Another thing I like about using a wrapper class is that it documents all the data that is stored in the session. The next programmer that comes along can see everything that is stored in the session just by looking at the wrapper class so you have less chance of storing the same data multiple times or refetching data that is already cached in the session.
Problem
How do I create a class library where I can get and set like the IIS `Session` object where I use `var x = objectname("key")` to get the value or `objectname("key") = x` to set the value?