【问题标题】:Windsor Optional Constructor ParametersWindsor 可选构造函数参数
【发布时间】:2010-12-11 08:00:09
【问题描述】:

如何让 Windsor 尊重可选的构造函数参数以进行注入?

我尝试制作一个 IContributeComponentModelConstruction 循环遍历每个构造函数的每个 ParameterInfo 并检查它是否为 IsOptional,然后相应地在 Windsor Dependency 对象上设置 IsOptional,但这似乎没有奏效。我仍然收到“由于依赖关系......等而无法实例化”。

谢谢。

更新:

我正在使用 Silverlight 4.0 的 2.5.2.0,并且可以通过以下方式重现:

    var container = new WindsorContainer();
    container.Register(Component.For<TestClass>());
    container.Resolve<TestClass>(); //boom

    public class TestClass
    {
        public TestClass(ITest test=null)
        {

        }
    }

    public interface ITest
    {

    }


Missing dependency.
Component TestClass has a dependency on ITest, which could not be resolved.
Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.

【问题讨论】:

    标签: .net dependency-injection castle-windsor


    【解决方案1】:

    在 v2.5.2 中可以。

    更新 我看了看并运行了您粘贴的代码,您是对的,它不起作用。 Windsor 确实正确地认识到该参数具有默认值。然而,Windsor 还有第二条规则,null 永远不是所需依赖项的有效值,而第二条规则在您的情况下胜出。

    这应该被认为是一个错误。

    要使其正常工作,您需要将 DefaultDependencyResolver 替换为您自己的。

    你需要重写两个方法:从DefaultDependencyResolver 非常像这样:

    public class AllowDefaultNullResolver : DefaultDependencyResolver
    {
        protected override bool CanResolveServiceDependency(CreationContext context, ComponentModel model, DependencyModel dependency)
        {
            return base.CanResolveServiceDependency(context, model, dependency) || dependency.HasDefaultValue;
        }
    
        protected override object ResolveServiceDependency(CreationContext context, ComponentModel model, DependencyModel dependency)
        {
            try
            {
                return base.ResolveServiceDependency(context, model, dependency);
            }
            catch (DependencyResolverException)
            {
                if(dependency.HasDefaultValue)
                {
                    return dependency.DefaultValue;
                }
                throw;
            }
        }
    }
    

    并使用此解析器而不是默认解析器。

    【讨论】:

    • 谢谢!它没有自定义贡献者,自动吗?还是我还需要自定义贡献者?
    • 仍然无法正常工作,请查看更新后的说明。谢谢。
    • 究竟什么是“用你自己的替换 DefaultDependencyResolver”?我已经将容器实例化为new WindsorContainer(new DefaultKernel(new AllowDefaultNullResolver(), new DefaultProxyFactory), new DefaultCompnentInstaller()),并且在传递空值时仍然得到 DependencyResolverException,因为 HasDefaultValue 为它们返回 false。一般来说,这个答案是不完整且具有误导性的。
    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    相关资源
    最近更新 更多