ASP.NET的MVC 3 HttpContext的包装 [英] ASP .Net MVC 3 HTTPContext Wrapper

查看:63
本文介绍了ASP.NET的MVC 3 HttpContext的包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在移动到TDD和单元测试code的努力我看过,我应该使用HttpContext的包装。在我服务层以及在我的控制器我访问HttpContext的会话的一些数据我都存储在那里。

In an effort to move to TDD and unit testable code I have read that I should be using an HttpContext wrapper. In my service layer as well as in my controllers I have to access the HttpContext Session for some data I have stored there.

有人可以提供一个HttpContext的包装实施MVC 3

Can someone provide an example of an HttpContext Wrapper implementation for MVC 3

推荐答案

的MVC运行时已经提供了的 HttpContextWrapper 。你需要实现什么是围绕会话状态的包装,并封装该国正在通过的HttpContext 访问的事实,这样您就可以使用DI或嘲弄的框架来创建一个非 - 的HttpContext 支持SessionWrapper为你的测试。 布拉德·威尔逊提供有关如何一些好的信息要做到这一点。但是,如果你不想通过视频(包含高级主题)涉水这里是包装届要点是:

The MVC Runtime already provides a HttpContextWrapper. What you need to implement is a wrapper around Session state, and encapsulate the fact that state is being accessed through HttpContext so that you can use DI or a Mocking framework to create a non-HttpContext backed SessionWrapper for your tests. Brad Wilson provides some good information on how to do this. However, if you don't want to wade through the video (which contains advanced topics) here is the gist for wrapping Session:

创建界面重新presenting强类型的对象,您可以通过会话通常访问:

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

创建一个使用会话作为后备存储的接口的实现:

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); }
    }

    ...
}

控制器使用 DependencyResolver (或preferably这是通过你做DI框架解决实例选择)。假设你在大多数控制器使用SessionWrapper,这可能在一个共同完成 BaseController

Resolve the instance in your Controller using DependencyResolver (or preferably this is done through you DI framework of choice). Assuming you are using the SessionWrapper in a majority of Controllers, this could be done in a common BaseController:

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

这篇关于ASP.NET的MVC 3 HttpContext的包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆