如何让microsoft unity“构造”给定接口类型的类列表。
非常简单的例子:
List<IShippingCalculation> list = new List<IShippingCalculation>();
list.Add(new NewYorkShippingCalculation());
list.Add(new FloridaShippingCalculation());
list.Add(new AlaskShippingCalculation());
//Not What I want
public void calcship(List<IShippingCalculation> list)
{
var info = new ShippingInfo(list);
info.CalculateShippingAmount(State.Alaska)
}
//Somehow in unity, must i do this for all the concrete classes?
//how does it know to give a list.
Container.RegisterType<IShippingInfo,new AlaskaShippingCalculation()>();??
//What I want
public void calcship(IShippingInfo info)
{
info.CalculateShippingAmount(State.Alaska)
}
三江源!
答案 0 :(得分:13)
如果您使用的是Unity 2,则可以使用ResolveAll<T>
Container.RegisterType<IShippingInfo,FloridaShippingCalculation>("Florida");
Container.RegisterType<IShippingInfo,NewYorkShippingCalculation>("NewYork");
Container.RegisterType<IShippingInfo,AlaskaShippingCalculation>("Alaska");
IEnumerable<IShippingInfo> infos = Container.ResolveAll<IShippingInfo>();
您必须为每个注册命名,因为ResolveAll只会返回命名注册。
答案 1 :(得分:11)
您不需要将容器作为参数,使用如上所述的名称注册具体类型,然后在构造函数中添加数组作为参数,IList或通用枚举不起作用。
public MyConstructor(IMyType[] myTypes)