2016-06-11 48 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