我有一个类,它接受一个IEnumerable
构造函数参数,我想用 Unity 解析它并注入一个对象数组。这些简单的类说明了这个问题。
public interface IThing
{
int Value { get; }
}
public class SimpleThing : IThing
{
public SimpleThing()
{
this.Value = 1;
}
public int Value { get; private set; }
}
public class CompositeThing : IThing
{
public CompositeThing(IEnumerable<IThing> otherThings)
{
this.Value = otherThings.Count();
}
public int Value { get; private set; }
}
假设我想将四个注入SimpleThing
到CompositeThing
. 我已经尝试了以下 Unity 配置的几种变体。
<alias alias="IThing" type="TestConsoleApplication.IThing, TestConsoleApplication" />
<alias alias="SimpleThing" type="TestConsoleApplication.SimpleThing, TestConsoleApplication" />
<alias alias="CompositeThing" type="TestConsoleApplication.CompositeThing, TestConsoleApplication" />
<container>
<register type="IThing" mapTo="SimpleThing" name="SimpleThing" />
<register type="IThing" mapTo="CompositeThing" name="CompositeThing">
<constructor>
<param name="otherThings">
<array>
<dependency type="SimpleThing"/>
<dependency type="SimpleThing"/>
<dependency type="SimpleThing"/>
<dependency type="SimpleThing"/>
</array>
</param>
</constructor>
</register>
</container>
但是我收到错误消息配置设置为注入数组,但类型 IEnumerable`1 不是数组类型。 如果我将构造函数参数更改为IThing[]
有效,但我不想这样做。我需要对我的 Unity 配置做些什么才能使其正常工作?