Unity Resolve Multiple Classes

时光总嘲笑我的痴心妄想 提交于 2020-01-01 04:56:27

问题


How do I get microsoft unity to 'construct' a list of classes for a given interface type.

Very Simple example:

  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)
  }

Thankyou!


回答1:


If you are using Unity 2 you can use ResolveAll<T>

Container.RegisterType<IShippingInfo,FloridaShippingCalculation>("Florida");
Container.RegisterType<IShippingInfo,NewYorkShippingCalculation>("NewYork");
Container.RegisterType<IShippingInfo,AlaskaShippingCalculation>("Alaska");

IEnumerable<IShippingInfo> infos = Container.ResolveAll<IShippingInfo>();

You have to give a name to every registration because ResolveAll will only return named registrations.




回答2:


You do not need to have the container as parameter, register the concrete types with names as said above, then in the constructor add a array as parameter, IList or generic Enum does not work.

public MyConstructor(IMyType[] myTypes)


来源:https://stackoverflow.com/questions/4206958/unity-resolve-multiple-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!