2016-06-11 89 views
2

我想知道我們該如何使用xml config將一個抽象類的所有子對象的List注入到構造函數中。c#Unity容器構造函數注入列表<childs>

例如爲:

Class Test 
{ 
public Test(List<A> instances) // So this list should have instance of B & C 
{ 

} 
} 

abstract Class A 
{ 

} 

Class B: A 
{ 

} 

Class C: A 
{ 

} 

謝謝!

+0

你的意思是B和C繼承A? –

+0

哎呀!糾正。謝謝。 – Deepak

回答

1

如果更改一個類型Test的構造函數參數上IList<A>您可以使用下面的配置:

<configuration> 
    <configSections> 
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> 
    </configSections> 
    <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <namespace name="System.Collections.Generic" /> 
    <namespace name="ConsoleApplication1" /> 
    <assembly name="ConsoleApplication1" /> 
    <container> 
     <register type="A" mapTo="B" name="B" /> 
     <register type="A" mapTo="C" name="C" /> 
     <register type="IList`1[[A]]" mapTo="A[]" /> 
    </container> 
    </unity> 
</configuration> 

因此,關鍵是要在A[]地圖IList<A>界面 - 請參閱this question瞭解詳情。

+0

謝謝你停止。我現在應該如何解決這個問題,以便Test構造函數獲得帶有B&C的列表? – Deepak

+0

我現在可以解決它,並且正在按照列表與B&C實例正確傳遞。謝謝你停止。 – Deepak