【问题标题】:Can I pass other components into Castle Windsor config?我可以将其他组件传递到 Castle Windsor 配置中吗?
【发布时间】:2015-05-13 02:10:59
【问题描述】:

假设我有一个我想以特定方式初始化的主要组件,我让它的构造函数为此目的使用一个接口。有没有办法在我的xml中定义我想要的这个接口的实现,然后将它作为参数注入到主组件中?像这样:

public interface IComponent2 {
    void DoStuff();
}

public class ConcreteCompImpl2 : IComponent2 {

    IComponent1 _comp;
    public ConcreteCompImpl2(IComponent1 comp) {
        _comp = comp;
    }

    public void DoStuff(){
        //do stuff
    }
}



<component id="component1" service="ABC.IComponent1, ABC" type="ABC.ConcreteCompImpl1, ABC" />
<component id="component2" service="ABC.IComponent2, ABC" type="ABC.ConcreteCompImpl2, ABC" >         
    <parameters>
       <component1>???</component1>
    </parameters>
</component>

或者我认为这一切都错了,有一种更简单的方法可以实现这一点?我希望能够做的主要事情是配置在创建 IComponent2 时将注入的 IComponent1 的“种类”。谢谢

【问题讨论】:

    标签: dependency-injection castle-windsor


    【解决方案1】:

    如果你只有一个实现IComponent1的具体类,那么当你解析IComponent2时它会自动注入。

    如果您有多个实现IComponent1 的类,并且每次解析IComponent2 时都需要一个特定的类,则需要指定一个inline dependency

    container.Register(
        Component.For<IComponent2>()
                 .ImplementedBy<Component2>()
                 .DependsOn(Dependency.OnComponent<IComponent1, YourSpecialComponent1>())
    );
    

    我不完全确定您可以在 XML 配置中指定它,但老实说,您应该使用 Fluent API 而不是 XML configuration,除非您有非常令人信服的理由来使用它。如上链接所述:

    在 XML 中注册组件的能力主要是 Windsor 早期在创建 Fluent Registration API 之前的遗留物。它远不如代码中的注册强大,许多任务只能通过代码完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多