我正在尝试在我的解决方案中使用DI(即Castle Windsor),但我遇到以下异常:
No component for supporting the service Company.Web.Controllers.DashboardController was found
尝试解析控制器时WindsorControllerFactory.GetControllerInstance()
发生此异常(即:(IController)_kernel.Resolve(controllerType);
)
然而,当我将DI安装程序和控制器工厂移动到asp.net应用程序并让该Web项目引用我的解决方案中的所有项目时,不会发生异常。
问题:如何解决上面的异常并将依赖注入及其配置放入其自己的程序集中(即:Company.Initialization)?
请随意提供任何可以改进代码的建设性批评。
当前解决方案项目设置
ControllersInstaller.cs
namespace Company.Initialization
{
public class ControllersInstaller : IWindsorInstaller
{
/// <summary>
/// Installs the controllers
/// </summary>
/// <param name="container"></param>
/// <param name="store"></param>
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(FindControllers().LifestyleTransient());
}
/// <summary>
/// Find controllers within this assembly in the same namespace as HomeController
/// </summary>
/// <returns></returns>
private BasedOnDescriptor FindControllers()
{
return AllTypes.FromAssemblyNamed("Company.Web")
.BasedOn<IController>()
.If(Component.IsInNamespace(@"Company.Web.Controllers"))
.If(t => t.Name.EndsWith("Controller"));
}
}
}
RepoInstaller.cs
namespace Company.Initialization
{
public class RepoInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(AllTypes.FromAssemblyNamed("Company.Services")
.Where(type => type.Name.EndsWith("Service"))
.WithService.DefaultInterfaces().LifestyleSingleton());
container.Register(AllTypes.FromAssemblyNamed("Company.NHibernateProvider")
.Where(type => type.Name.EndsWith("Repository"))
.WithService.DefaultInterfaces().LifestyleSingleton());
}
}
}
WindsorControllerFactory.cs
namespace Company.Initialization
{
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel;
/// <summary>
/// Constructor
/// </summary>
/// <param name="kernel"></param>
public WindsorControllerFactory(IKernel kernel)
{
_kernel = kernel;
}
/// <summary>
/// Release the controller at the end of it's life cycle
/// </summary>
/// <param name="controller">The Interface to an MVC controller</param>
public override void ReleaseController(IController controller)
{
_kernel.ReleaseComponent(controller);
}
/// <summary>
/// Resolve a controller dependency
/// </summary>
/// <param name="requestContext">The HTTP context</param>
/// <param name="controllerType">Type of controller to resolve</param>
/// <returns>IController</returns>
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);
}
}
}