I have two types of session wrappers:
Type 1
public class SessionHandler
{
public static SessionHandler CurrentSession
{
get
{
SessionHandler session =
(SessionHandler)HttpContext.Current.Session["SessionId"];
if (session == null)
{
session = new SessionHandler();
HttpContext.Current.Session["SessionId"] = session;
}
return session;
}
}
public int? UserId { get; set; }
}
Type 2
public static class SessionHandler
{
private static void SetSession<T>(string sessionId, T value)
{
HttpContext.Current.Session[sessionId] = value;
}
private static T GetSession<T>(string sessionId)
{
return (T)HttpContext.Current.Session[sessionId];
}
public static int? UserId
{
get
{
return GetSession<int>("UserId");
}
set
{
SetSession<int>("UserId", value);
}
}
}
The usage is as follows:
//Type 1
SessionHandler.CurrentSession.UserId = 10;
//Type 2
SessionHandler.UserId = 10;
Please suggest which one is better and why.
What I think about type 1:
Good for readability and maintainability. I can add more properties with less efforts, but the session will become heavy (single session for whole application). This approach may not be good, if we have more sessions to store. However, I'm not sure whether assignment/retrieving the session is just changing the reference or does some serialization/de-serialization.
What I think about type 2:
Usage is easy, but it needs little work while adding more sessions. This is the same as a normal session usage but, it just avoids the typos which might happen frequently while retrieving the sessions on various places.
Type 1
allows for inheritance, interface implementation and overall a better way to do unit testing.static
classes should only be used when there is absolutely, positively, no way state needs to be maintained. Also, please note that the way it is written, it is not thread-safe. \$\endgroup\$