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?
I guess, you could use a generic dictionary like Dictionary<string, Object>
or something similar to achieve this effect. You would have to write some wrapper code to add an Object when accessing a non-existend item by for example a custom default property in your Wrapper.
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.
You could use some thing like this
public class Session
{
private static Dictionary<string, object> _instance = new Dictionary<string, object>();
private Session()
{
}
public static Dictionary<string, object> Instance
{
get
{
if(_instance == null)
{
_instance = new Dictionary<string, object>();
}
return _instance;
}
}
}
And use it like this
Session.Instance["key"] = "Hello World";