2011-02-17 67 views
2

以下情形:溫莎城堡地圖命名組件特定的屬性

我們用流利的API來註冊在裝配和兩個部件tyepof(A)與名爲鍵的所有組件。另一個具有兩個typeof(A)屬性的類B應該注入已命名的組件。

樣品:

public class A : IA {} 

public class B : IB 
{ 
    [Named("first")] 
    public IA First { get; set; } 

    [Named("second")] 
    public IA Second { get; set; } 
} 

// ... 

container.Register(Component.For<IA>().Instance(new A(value1)).Named("first")); 
container.Register(Component.For<IA>().Instance(new A(value2)).Named("second")); 

// ... 
var b = container.Resolve<IB>(); // named instances of A get injected to B using the Named attribute 

這是可能與屬性像命名或僅與XML配置?

+0

順便說一句`B`應該注入`IA`,而不是具體的`A` – 2011-02-17 15:29:16

+0

沒錯,這實際上是我想要輸入的內容。 ;) 修復。 – 2011-02-18 14:02:37

回答

4

在溫莎這樣做的標準方法是使用service overrides。在您的例子,當你註冊B你會做這樣的:

container.Register(Component.For<IB>().ImplementedBy<B>() 
        .ServiceOverrides(new {First = "first", Second = "second"})); 

(還有其他的方式來表達這一點,檢查鏈接的文檔)

使用Named屬性爲您提出污染與無關的擔憂代碼(B不應該關心什麼A小號獲得注入)

1

這裏是你將如何解決使用DependsOn並納入nameof表達(介紹了C#6.0)這個問題:

container.Register 
(
    Component.For<IA>() 
     .Instance(new A(value1)) 
     .Named("first"), 
    Component.For<IA>() 
     .Instance(new A(value2)) 
     .Named("second"), 
    Component.For<IB>() 
      .ImplementedBy<B>() 
      .DependsOn 
      (
       Dependency.OnComponent(nameof(B.First), "first"), 
       Dependency.OnComponent(nameof(B.Second), "second") 
     )  
) 

Dependency.OnComponent有許多覆蓋,但在這種情況下,第一個參數是屬性名稱,第二個參數是組件名稱。

有關更多文檔,請參閱here