Search code examples
asp.net-mvccastle-windsorhttpcontexts#arp-architecture

Castle.Windsor and HttpContextWrapper


HttpContextWrapper and HttpContextBase, as explained here, were introduced to make HttpContext more mockable/testable.

I'm trying to use it with S#arp Architecture, and hitting some problems.

My MVC Controllers are set up to accept an HttpContextBase argument in the constructor, and during Application_Start, HttpContextBase is registered with Castle.Windor as follows:

container.Register(Component.For<HttpContextBase>().UsingFactoryMethod(
    () => new HttpContextWrapper(HttpContext.Current)));

This seemed to work OK for a bit, but then I realised Castle is only running that Factory method once, so all requests get the original HttpContextWrapper. Really it needs to be re-created for every request. The Castle.Windsor command for that would be:

container.Register(Component.For<HttpContextBase().
    LifeStyle.PerWebRequest.UsingFactoryMethod(
    () => new HttpContextWrapper(HttpContext.Current)));

... but it turns out that Castle.Windsor doesn't allow LifeStyle.PerWebRequest to be used within Application_Start (as explained here)

What should I be doing? Is there an easy way round this or should I give up on HttpContextWrapper and inject my own factory to make new ones as needed?


Solution

  • My MVC Controllers are set up to accept an HttpContextBase argument in the constructor

    You gotta be doing something extremely wrong here, so stop before it's too late and damage has been caused (material, moral and human casualties :-)). You already have the HttpContext inside the controller.

    Don't register any HttpContexts in your DI framework. The HttpContext handling is the job of ASP.NET.