2015-05-12 85 views
1

可以说我有一个主要的组件,我想以特定的方式进行初始化,我有它的构造函数为此接口。有没有一种方法可以在我的xml中为此接口定义我想要的实现,并将其作为参数注入到主要组件中?像这样:我可以将其他组件传递到Castle Windsor配置吗?

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> 

或者我在想这一切都是错误的,还有一个更简单的方法来完成这个?我希望能够做的主要事情是配置什么样的IComponent1将被注入IComponent2创建。谢谢

回答

1

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

如果你有几个类实现IComponent1,想一个特定每次IComponent2得到解决,需要特定的inline dependency

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

我不能完全肯定,你可以在XML配置文件指定该,但说实话,你应该使用Fluent API而不是XML configuration,除非你有一个非常有说服力的理由来使用它。正如上面提到的链接:

在创建Fluent注册API之前,在XML中注册组件的能力大多是从Windsor早期剩余的。它比代码中的注册功能强大得多,许多任务只能通过代码完成。

相关问题