views:

27

answers:

1

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";
A: 

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.

Darin Dimitrov
I believe he's trying to mimic the existing model. Where `AppHttpContext.Current.Session["blah"]` simply replaces `HttpContext.Current.Session["blah"]` references. Could you elaborate on your suggestion possibly with code and usage? I could be misreading it a bit.
Anthony Pegram