c# Unity容器构造函数注入list<childs>
c# Unity container constructor injection of list<childs>
我想知道如何使用 xml 配置将抽象 class 的所有子对象的列表注入构造函数。
例如:
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
{
}
谢谢!!!
如果您在 IList<A>
上更改 Test
的构造函数参数的类型,则可以使用以下配置:
<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。
我想知道如何使用 xml 配置将抽象 class 的所有子对象的列表注入构造函数。
例如:
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
{
}
谢谢!!!
如果您在 IList<A>
上更改 Test
的构造函数参数的类型,则可以使用以下配置:
<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。