ASP.NET MVC 3 HTTPContext Wrapper

In an attempt to switch to TDD and the module of the tested code, I read that I should use the HttpContext shell. In my service, as well as in my controllers, I have to access the HttpContext session for some of the data that I saved there.

Can anyone provide an example implementation of the HttpContext Wrapper for MVC 3

+3
source share
1 answer

MVC Runtime already provides an HttpContextWrapper . What you need to implement is a wrapper around the session state and encapsulates the fact of accessing the state through HttpContextso that you can use the DI or the Mocking framework to create an unconverted SessionWrapper HttpContextfor your tests. Brad Wilson gives some good information on how to do this . However, if you do not want to wade through a video (containing advanced topics), here is the gist for a session session:

Create an interface representing a strongly typed object, which you can usually access through a session:

public interface ISessionWrapper
{
    public UserPreferences CurrentUserPreferences{get;set;}
    ...
}

Create an implementation of an interface that uses Session as the backup storage:

public class HttpContextSessionWrapper : ISessionWrapper
{
    private T GetFromSession<T>(string key)
    {
        return (T) HttpContext.Current.Session[key];
    }

    private void SetInSession(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public UserPreferences CurrentUserPreferences
    {
        get { return GetFromSession<UserPreferences>("CurrentUserPreferences"); }
        set { SetInSession("CurrentUserPreferences", value); }
    }

    ...
}

Controller DependencyResolver (, , DI). , SessionWrapper , BaseController:

var SessionWrapper = DependencyResolver.Current.GetService<ISessionWrapper>();
+5

All Articles