开发者

Unity Resolve Multiple Classes

开发者 https://www.devze.com 2023-01-25 08:13 出处:网络
How do I get microsoft unity to \'construct\' a list of classes for a given interface type. Very Simple example:

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开发者_Go百科.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!


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消