开发者

Is it safe to always create a new HttpContextWrapper?

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<Http开发者_运维百科ContextBase> 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.


private readonly Func<HttpContextBase> _httpContext = () =>
    new HttpContextWrapper(HttpContext.Current);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜