Я делаю это, используя ControllerBuilder.SetControllerFactory
и код, который вы можете найти в проекте с открытым исходным кодом MvcContrib :
Global.asax.cs
protected void Application_Start()
{
...
IWindsorContainer windsorContainer = new WindsorContainer();
windsorContainer.RegisterControllers(Assembly.GetExecutingAssembly());
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(windsorContainer));
...
}
WindsorControllerFactory
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IWindsorContainer _container;
public WindsorControllerFactory(IWindsorContainer container)
{
if (container == null)
{
throw new ArgumentNullException();
}
_container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException();
}
if (!typeof(IController).IsAssignableFrom(controllerType))
{
throw new ArgumentException();
}
try
{
return (IController)_container.Resolve(controllerType);
}
catch (Exception ex)
{
throw new InvalidOperationException();
}
}
public override void ReleaseController(IController controller)
{
IDisposable disposable = controller as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
_container.Release(controller);
}
}
WindsorExtensions (см. MvcContrib )
public static class WindsorExtensions
{
public static IWindsorContainer RegisterController<T>(this IWindsorContainer container) where T : IController
{
container.RegisterControllers(typeof(T));
return container;
}
public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Type[] controllerTypes)
{
foreach (Type type in controllerTypes)
{
if (ControllerExtensions.IsController(type))
{
container.Register(Component.For(type).Named(type.FullName).LifeStyle.Is(LifestyleType.Transient));
}
}
return container;
}
public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Assembly[] assemblies)
{
foreach (Assembly assembly in assemblies)
{
container.RegisterControllers(assembly.GetExportedTypes());
}
return container;
}
}
ControllerExtensions (см. MvcContrib )
public static class ControllerExtensions
{
public static bool IsController(Type type)
{
return type != null
&& type.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
&& !type.IsAbstract
&& typeof(IController).IsAssignableFrom(type);
}
}