我第一次尝试设置 Castle Windsor,但遇到了一些问题。我的解决方案中有三个项目:
- 领域
- 达尔
- 网络
这些服务位于 DAL。它们都继承自IService
. (UserService
工具IUserService
,IUserService
工具IService
)。Web 应用程序是一个 MVC 5 应用程序。所有控制器都继承自BaseController
.
我使用这篇文章来帮助我设置 Windsor,但我不断收到异常:
Castle.Windsor.dll 中出现“Castle.MicroKernel.ComponentNotFoundException”类型的异常,但未在用户代码中处理
附加信息:找不到支持服务 Solution.Web.Controllers.HomeController 的组件
奇怪的是控制器的路径是正确的。
下面是我的配置代码:
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);
}
}
非常感谢任何正确方向的帮助或指导!