我有一個類需要一個IEnumerable
構造函數參數,我想用Unity解析並注入一個對象數組。這些簡單的類說明了這個問題。如何配置Unity爲IEnumerable注入數組
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; }
}
說我要注入4 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配置做些什麼才能使其發揮作用?
可能的重複[解決IEnumerable與Unity](http://stackoverflow.com/questions/1961549/resolving-ienumerablet-with-unity) –
2011-12-15 11:57:15
我不認爲這是重複的,因爲該問題是關於程序註冊而我使用的配置文件。 – batwad 2011-12-15 12:17:43