c# Unity 容器构造函数注入列表<childs>



我想知道如何使用 xml 配置将抽象类的所有子对象的 List 注入构造函数。

例如:

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>界面 - 有关详细信息,请参阅此问题。

相关内容

最新更新