I've been reading a couple of renditions of this SessionWrapper class via DotNetKicks over the past couple of days. While I must admit that this code isn't 100% original, I can say that I have given it a more generic feel and added a little bit of functionality. With my implementation you can not only use any class, you can specify a name for the session object. That way if you want to store say the Account and Order objects in Session you could use the same method without creating a wrapper for each type.
Account
Order
using System.Web; namespace NamespaceNameGoesHere{ public class Session<T> where T: class { private string _name = string.Empty; public string Name { get { return _name; } set { _name = value; } } public T Object { get { return HttpContext.Current.Session[Name] as T ?? null; } set { HttpContext.Current.Session[Name] = value; } } public Session(string name) { _name = name; } public Session() { } }}
using
namespace
public string Name { get { return _name; } set { _name = value; } }
public T Object { get { return HttpContext.Current.Session[Name] as T ?? null; } set { HttpContext.Current.Session[Name] = value; } }
public Session() { } }}
Pretty straight-forward. Here's how you would use it from a Page_Load for example:
Page_Load
Session<Foo> session = new Session<Foo>("Foo"); if (session.Object == null) session.Object = new Foo(-1, "hai guyz!");else{ Foo foo = session.Object;}
Session
if (session.Object == null) session.Object = new Foo(-1, "hai guyz!");else{ Foo foo = session.Object;}
Not cutting-edge but could be useful if you want a type-safe session state.
Remember Me
Powered by: newtelligence dasBlog 2.0.7226.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Your Name Here
E-mail