>域名
> DAL
>网络
这些服务位于DAL.他们都继承自IService. (UserService实现IUserService,IUserService实现IService). Web应用程序是MVC 5应用程序.所有控制器都继承自BaseController.
我使用this帖子帮我设置温莎,但我一直得到例外:
An exception of type ‘Castle.MicroKernel.ComponentNotFoundException’ occurred in Castle.Windsor.dll but was not handled in user code
Additional information: No component for supporting the service Solution.Web.Controllers.HomeController was found
奇怪的是控制器的路径是正确的.
以下是我的配置代码:
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); } } public class ControllersInstaller : IWindsorInstaller { public void Install(IWindsorContainer container,IConfigurationStore store) { container.Register( Classes.FromThisAssembly() .BasedOn(typeof(BaseController)) .LifestyleTransient()); } } public class ServiceInstaller : IWindsorInstaller { public void Install(IWindsorContainer container,IConfigurationStore store) { container.Register(Types.FromAssemblyContaining(typeof(IService).GetType()) .BasedOn<IService>().WithService.FromInterface() .LifestyleTransient() ); } }
在Global.asax中:
public class MvcApplication : System.Web.HttpApplication { private static IWindsorContainer container; protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Setup Castle.Windsor IOC MvcApplication.BootstrapContainer(); } protected void Application_End() { container.Dispose(); } private static void BootstrapContainer() { container = new WindsorContainer().Install(FromAssembly.This()); container.Install(FromAssembly.Containing(typeof(IService).GetType())); var controllerFactory = new WindsorControllerFactory(container.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); } }
非常感谢任何正确方向的帮助或指导!
解决方法
return (IController)kernel.Resolve(controllerType);
你要求城堡用英语做的是“给我实现由controllerType定义的服务的组件”.
问题出在您的控制器注册中.
container.Register( Types.FromThisAssembly() .BasedOn(typeof(BaseController)) .WithServices(typeof(BaseController)) .LifestyleTransient());
在这个块中,您告诉castle注册实现BaseController的所有类型,并且它们公开的服务也是BaseController.
因此,Castle正在寻找一个满足服务HomeController的组件,并且无法找到任何东西,因为您获得的唯一服务是BaseController.
长话短说,如果你删除
.WithServices(typeof(BaseController))
Castle将假设您的每个控制器都是一项服务,然后您可以按照您想要的方式请求实现控制器的组件.
作为单独的注释,为了清楚起见,我将Types.FromThisAssembly()更改为Classes.FromThisAssembly(),因为您只查找类将扫描的类,而不是stucts / classes / interfaces等.