我正在使用Castle Windsor 3.0,它对我来说非常有效,直到我尝试注册控制器(我使用WCF工具和IoC作为存储库/服务层)。这是我的控制器安装程序类:
public class ControllersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
RegisterAllBasedOnWithCustomComponentRegistration(container, typeof(IController),
typeof(HomeController).Assembly,
cr => cr.LifeStyle.Transient);
}
private void RegisterAllBasedOnWithCustomComponentRegistration(IWindsorContainer container, Type baseType,
Assembly assemblyWithImplementations, Func<ComponentRegistration, ComponentRegistration<object>> customComponentRegistrationCb)
{
container.Register(
AllTypes.FromAssembly(assemblyWithImplementations)
.BasedOn(baseType)
.If(t => t.Name.EndsWith("Controller"))
.Configure(c => customComponentRegistrationCb(c)));
}
}
这是我的控制器工厂:
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel;
public WindsorControllerFactory(IKernel kernel)
{
_kernel = kernel;
}
public override void ReleaseController(IController controller)
{
_kernel.ReleaseComponent(controller);
}
public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
var controllerComponentName = controllerName + "Controller";
return _kernel.Resolve<IController>(controllerComponentName);
}
}
从我的global.asax我调用下一个方法:
InversionOfControl.InstallControllers(FromAssembly.This());
位于另一个项目中。在那里我打电话给安装代码:
public static void InstallControllers(IWindsorInstaller install)
{
_container.Install(install);
}
似乎我做错了什么,我希望我是因为它可能是一个“永远不会再次使用awny beta”的时刻。
我得到了下一个异常:没有找到支持System.Web.Mvc.IController服务的组件尽管我可以看到调试模式下的控制器正在容器中注册
答案 0 :(得分:9)
在你的ControllerFactory中,你不应该解析IController
而应该是具体的控制器类型。这是我一直使用的典型的基于Windsor的ControllerFactory:
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IWindsorContainer _container;
public WindsorControllerFactory(IWindsorContainer container)
{
_container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (IController)_container.Resolve(controllerType);
}
public override void ReleaseController(IController controller)
{
_container.Release(controller);
}
}
答案 1 :(得分:1)
在这种情况下,添加.WithServices(typeof(IController))并命名所有组件。
cr => cr.LifeStyle.Transient.Named(cr.Implementation.Name)
您的注册应如下所示:
.Register(
AllTypes.FromAssembly(assemblyWithImplementations)
.BasedOn(baseType)
.WithServices(typeof(IController))
.If(t => t.Name.EndsWith("Controller"))...)