I'm going over Sanderson's Pro ASP.NET MVC Framework and in Chapter 4 he discusses Creating a Custom Controller Factory and it seems that the original method, AddComponentLifeStyle
or AddComponentWithLifeStyle
, used to register controllers is deprecated now:
public class WindsorControllerFactory : DefaultControllerFactory
{
IWindsorContainer container;
public WindsorControllerFactory()
{
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
// register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
//[Obsolete("Use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)) instead.")]
//IWindsorContainer AddComponentLifeStyle<I, T>(string key, LifestyleType lifestyle) where T : class;
foreach (Type t in controllerTypes)
{
container.Register(Component.For<IController>().ImplementedBy<???>().Named(t.FullName).LifeStyle.Is(LifestyleType.Transient));
}
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
The new suggestion is to use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle))
, but I can't figure out how to present the implementing controller type in the ImplementedBy<???>()
method. I tried ImplementedBy<t>()
and ImplementedBy<typeof(t)>()
, but I can't find the appropriate way to pass in the implementing type. Any ideas?
You may also want to consider using the new installer option in the latest Windsor build. There is more documentation on Windsor's tutorial: http://stw.castleproject.org/Windsor.Windsor-tutorial-part-three-writing-your-first-installer.ashx
something like:
ControllersRegistrarMarker is just an empty class in your Controllers assembly
There's a tutorial (in the works but 9 parts are already out) that discusses usage of Windsor in ASP.NET MVC here. That's the most up to date and covering most of the usual usage resource on the topic as far as I'm aware.
I'm doing this using the
ControllerBuilder.SetControllerFactory
and the code you can find in the open source project MvcContrib:Global.asax.cs
WindsorControllerFactory
WindsorExtensions (see MvcContrib)
ControllerExtensions (see MvcContrib)
@Lirik, as an addition: drop your own custom
IControllerFactory
out if you use MVC3. Just register controllers with Windsor and implementIDependencyResolver
with Windsor container inside.Set your
IDependencyResolver
as MVC DependencyResolver andDefaultControllerFactory
will automatically wire up controllers registered in container (viaDependencyResolver
).