Search code examples
asp.netasp.net-mvcsessionhttpcontext

Creating a Wrapper For HttpContext


Basically I'm trying to create a SessionManager class which I can use to manage sessions in my MVC applications. For that I'm thinking the best way of doing so is by creating a wrapper class for HttpContext which would then allow me to access HttpContext.Current.Session.

To be honest, I'm not really sure about the whole thing, I just feel it's the logical way of doing so. I also want to create an ISessionManager and ISession interfaces, and then implement them according to my application's needs. For my current project, and for now, I need a InProc session management, but I might need to store session data in MSSQL Server when we decide to expand and use a web farm or a garden. That's why I'm trying to build a sort of an extensible framework right from the start.

Final note, I will be using Microsoft Unity to inject the concrete SessionManager of choice. I believe that's a good way to maintain a certain level of abstraction.

Any suggestions for achieving all that?

Thanks in advance! :)


Solution

  • Ok here's what I came up with, but I'm not sure that's the right way of doing this so your opinions are most welcome!

    ISessionManager:

    public interface ISessionManager  
    {      
        void RegisterSession(string key, object obj);       
        void FreeSession(string key);   
    }
    

    SessionManager:

    public class SessionManager : ISessionManager
    {
        private IDictionary<string, object> sessionDictionary;
    
        public SessionManager(IDictionary<string, object> _sessionDictionary)
        {
            sessionDictionary = _sessionDictionary;
        }
    
        public IDictionary<string, object> Session
        {
            get
            {
                return sessionDictionary;
            }
        }
    
        public void RegisterSession(string key, object obj)
        {
            sessionDictionary[key] = obj;
        }
    
        public void FreeSession(string key)
        {
            sessionDictionary[key] = null;
        }
    }
    

    Then when I want to instantiate the class (inside my web app), I would do something like that:

    var sessionManager = new SessionManager(HttpContext.Current.Session);
    sessionManager.RegisterSession["myKey"] = someObject;
    

    But I would prefer to avoid using magic strings as the key. I could include a constant string property like sessionKey = "myKey" in the class, but that would mean I could only store one object in the session manager, right?

    Feedback please. :)