Castle Windsor kernel.Resolve不解析类型

时间:2014-07-01 14:28:00

标签: c# asp.net-mvc castle-windsor

我正在使用DI Castle Windsor(版本2.5.1.0)开发MVC应用程序。在WindsorControllerFactory中,我有以下代码,

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);
}

我收到以下异常

Castle.MicroKernel.ComponentNotFoundException occurred
  HResult=-2146233088
  Message=No component for supporting the service NN.XX.YController was found
  Source=Castle.Windsor
  StackTrace:
       at Castle.MicroKernel.DefaultKernel.Resolve(Type service)
       at Permal.BSG.Manager.WebUI.WindsorControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in c:\Dev\Apps\WindsorControllerFactory.cs:line 61
  InnerException:

但是,当我用以下内容替换kernel.Resolve时,它可以正常工作

return (IController)kernel.Resolve(controllerType.FullName, new Dictionary<string,string>());

任何人都可以帮我解决这个问题,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

由于错误的类型注册,您遇到此问题。

.WithService.Self()应该使用而不是.WithService.FromInterface(),因为ControllerFactory尝试使用它来解析控制器的具体controllerType(例如YController) )。

return (IController)kernel.Resolve(controllerType);

我通常使用以下注册:

container.Register(AllTypes.FromThisAssembly()
    .BasedOn<IController>()
    .WithService.Self()
    .Configure(it => it.LifeStyle.Transient));