我阅读了有关Casle Windsor的this文章。所以我有类BusinessLogicInstaller.cs,ControllersInstaller,IocContainer和WindsorControllerFactory。这是一个例子:
public class ControllersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(AllTypes.FromThisAssembly()
.Pick().If(t => t.Name.EndsWith("Controller"))
.Configure(configurer => configurer.Named(configurer.Implementation.Name))
.LifestylePerWebRequest());
}
}
public class BusinessLogicInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component
.For<IUser>()
.ImplementedBy<User>());
}
}
public static class IocContainer
{
private static IWindsorContainer _container;
public static void Setup()
{
_container = new WindsorContainer().Install(FromAssembly.This());
WindsorControllerFactory controllerFactory = new WindsorControllerFactory(_container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
}
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel;
public WindsorControllerFactory(IKernel kernel)
{
this._kernel = kernel;
}
public override void ReleaseController(IController controller)
{
_kernel.ReleaseComponent(controller);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
}
return (IController)_kernel.Resolve(controllerType);
}
}
在Global.asax类我有
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Add this line to Application_Start in Global.asax.cs to setup the IoC Container.
IocContainer.Setup();
}
}
问题出在这行代码中的WindsorControllerFactory.cs类中:
return (IController)_kernel.Resolve(controllerType);
错误是没有组件支持服务Controllers.HomeController被找到。错误在哪里?
答案 0 :(得分:0)
我找到了解决方案......首先,我没有提到我的MVC项目中的一个重大区别(因为我不知道为什么这么重要) - 我为控制器提供了单独的程序集。因此,ControllerInstallers.cs
中的这部分代码出现了错误:
.FromThisAssembly()
应该是:
.FromAssemblyNamed("Controllers")
我要感谢@Jan Muncinsky,因为你的答案,以及你对一个问题所在的课程的暗示。