HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Session Wrapper

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wrappersessionstackoverflow

Problem

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(string sessionId, T value)
    {
        HttpContext.Current.Session[sessionId] = value;
    }

    private static T GetSession(string sessionId)
    {
        return (T)HttpContext.Current.Session[sessionId];
    }

    public static int? UserId
    {
        get
        {
            return GetSession("UserId");
        }
        set
        {
            SetSession("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.

Solution

private static T GetSession(string sessionId)
{
    return (T)HttpContext.Current.Session[sessionId];
}


The above code will throw an exception if the value is not present.

Consider something like the following:

private static T GetSession(string sessionId)
    {
        T val = default(T);
        var session = HttpContext.Current.Session;

        if (session[sessionId] != null)
        {
            val = (T)session[sessionId];
        }

        return val;
    }

Code Snippets

private static T GetSession<T>(string sessionId)
{
    return (T)HttpContext.Current.Session[sessionId];
}
private static T GetSession<T>(string sessionId)
    {
        T val = default(T);
        var session = HttpContext.Current.Session;

        if (session[sessionId] != null)
        {
            val = (T)session[sessionId];
        }

        return val;
    }

Context

StackExchange Code Review Q#11060, answer score: 2

Revisions (0)

No revisions yet.