它是安全的总是创建一个新的HttpContextWrapper? [英] Is it safe to always create a new HttpContextWrapper?

查看:139
本文介绍了它是安全的总是创建一个新的HttpContextWrapper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使现有的ASP.NET Web窗体应用程序通过使用一些ASP.NET MVC对象的可测试更多的单位,特别是HttpContextWrapper。我已经看到了它的用法的例子,他们总是创造一个新的对象。我拆开与反射源,看看它是所有存储传递的HttpContext。但我很好奇它是否是安全的总是创建HttpContextWrapper的新实例或按照Singleton模式不知何故?下面是类我用我的应用程序

 公共静态类AppHttpContext {
    公共静态HttpContextBase当前{{返回吸气剂(); }}    公共静态无效SetContext(Func键< HttpContextBase>吸气){
        吸气=吸收剂;
    }    私有静态函数功能:LT; HttpContextBase>消气=()=>新HttpContextWrapper(HttpContext.Current);
}

和我用它类似于HttpContext.Current

  AppHttpContext.Current.Session [嗒嗒] =东西;


解决方案

AppHttpContext 类是优秀的。它完美地抽象化的HttpContext,并允许单元测试。它是安全的使用 HttpContextWrapper 。作为改进你可以把这个类非静态的而不是静态和 SetContext 方法,你可以注入委托到构造。那么需要与环境(通常那些应该只限于你的Web窗体页)工作的各阶层可以采取的一个实例 AppHttpContext

I'm trying to make an existing ASP.NET web forms app more unit testable by using some of the ASP.NET MVC objects, specifically HttpContextWrapper. I've seen examples of its usage and they always create a new object. I disassembled the source with Reflector and see all it does is store the passed HttpContext. But I was curious as to whether or not it's safe to always create a new instance of HttpContextWrapper or follow the singleton pattern somehow? Below is the class I'm using in my app

public static class AppHttpContext {
    public static HttpContextBase Current { get { return Getter(); } }

    public static void SetContext(Func<HttpContextBase> getter) {
        Getter = getter;
    }

    private static Func<HttpContextBase> Getter = () => new HttpContextWrapper(HttpContext.Current);
}

And I use it similar to HttpContext.Current

AppHttpContext.Current.Session["blah"] = "something";

解决方案

Your AppHttpContext class is excellent. It perfectly abstracts the HttpContext and allows unit testing. It is safe to use HttpContextWrapper. As an improvement you could make this class non-static and instead of having a static SetContext method you could inject the delegate into the constructor. Then all classes that need to work with the context (normally those should only be limited to your webform pages) could take an instance of AppHttpContext.

这篇关于它是安全的总是创建一个新的HttpContextWrapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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