2015-05-12 84 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早期剩餘的。它比代碼中的註冊功能強大得多,許多任務只能通過代碼完成。

相關問題