无法创建组件,因为它具有要满足的依赖性。未提供的参数

时间:2016-05-18 05:16:37

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 castle-windsor windsor-3.0

我刚开始使用Windsor来解决依赖问题。但是我在控制器中传递字符串值时遇到错误。我检查了几个类似的温莎邮报,但没有运气。

public class HomeController : Controller
{
    public readonly String _A = string.Empty;
    public HomeController(string A)
    {
        this._A = A;        
    }
}

安装

public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .BasedOn<IController>()
            .LifestyleTransient());
    } 

WindsorControllerFactory

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

我需要包装&#39; A&#39;在课堂内并解决它的相应界面?

2 个答案:

答案 0 :(得分:2)

是的,这将是更好的解决方案,因为它使依赖非常明确。

public class HomeControllerConfig
{
    public string A { get; set; }
}

public class HomeController : Controller
{
    public readonly String _A = string.Empty;
    public HomeController(HomeControllerConfig config)
    {
        this._A = config.A;        
    }
}

安装

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    ...
    container.Register(Component.For<HomeControllerConfig>().Instance(new HomeControllerConfig { A = "..." }));
} 

答案 1 :(得分:0)

这取决于A对于您的应用程序的语义,但简而言之,不是 - 您不必包装它。 The documentation explains in detail如何配置它。