Way to fill collection with Unity

后端 未结 4 509
粉色の甜心
粉色の甜心 2020-12-09 05:06

I have two example classes

class ClassToResolve
{
    private List _coll;

    public ClassToResolve(List coll)
          


        
4条回答
  •  庸人自扰
    2020-12-09 05:46

    Unity will understand that T[] (array) dependencies are a list of things (but not IEnumerable, nor List). When you change the constructor of ClassToResolve to take an CollectionItem[] instead of a List you can configure your CollectionItem types as follows:

    container.RegisterType("a");
    container.RegisterType("b");
    container.RegisterType("c");
    container.RegisterType("d");
    

    The trick here is to name all the registrations. A default (nameless) registration will never be part of a sequence dependency in Unity.

    Now you can resolve ClassToResolve without the need to register it:

    container.Resolve();
    

    If you rather inject List you can add the following registration:

    container.RegisterType, CollectionItem[]>();
    

    And for IEnumerable you can add the following line:

    container
      .RegisterType, CollectionItem[]>();
    

提交回复
热议问题