Tuesday, 28 September 2010

Controller Factory for Castle Windsor v2.5.0, with HttpContext Resolution/Injection

The code below defines an object that holds an instance of the Castle Windsor container and sets it up to handle all requests to resolve ASP.NET MVC Controllers.  It also includes code to inject instances of HttpRequest and HttpContextBase.  This means that you can define injected objects that contain references to HttpContextBase in their constructors (which can be your MVC controllers) and they will receive populated instances of these objects.  It is worth noting that if you reference an instance of HttpContext that has not been resolved / injected by your IoC container then there is a high likely hood that you will end up with two or more separate instances which will cause problems (see this article on Injecting into Action Filter Attributes that can suffer this issue).

Please feel free to use this code and let me know if you run into any issues or have recommendations on how it could be improved.

public class WindsorControllerFactory : DefaultControllerFactory
IWindsorContainer Container { get; set; }

public WindsorControllerFactory(IWindsorContainer container)
Container = container;
Container.Register(AllTypes.FromThisAssembly().BasedOn(typeof(IController)).Configure(c => c.LifeStyle.Is(LifestyleType.Transient)));

.UsingFactoryMethod(() => new HttpRequestWrapper(HttpContext.Current.Request)));

.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));

Container.Register(Component.For<HttpContext>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => HttpContext.Current));

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
return (IController)Container.Resolve(controllerType);

public override void ReleaseController(IController controller)

This can then just be simple called by adding the following to your global.asax code.  Note: This expects a “castle” section to be defined in your web.config to resolve non-controller references handled within the WindsorControllerFactory.

public static IWindsorContainer WindsorContainer { get; private set; }

protected void Application_Start()
WindsorContainer = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(WindsorContainer));


Krzysztof Ko┼║mic said...

Instead of AllTypes.FromAssembly(Assembly.GetExecutingAssembly())

you can call AllTypes.FromThisAssembly()

also you don't need FactorySupportFacility.

Paul Hadfield said...

Thanks Krzysztof, have updated article and more importantly my code.

g said...

Thanks Paul, this is just what I was looking for.


Post a Comment