Way to fill collection with Unity

vitidev picture vitidev · Jun 10, 2011 · Viewed 9.4k times · Source

I have two example classes

class ClassToResolve
{
    private List<CollectionItem> _coll;

    public ClassToResolve(List<CollectionItem> coll)
    {
        _coll = coll;
    }
}

class CollectionItem
{
    //...
}

and I need to resolve ClassToResolve

var classToResolve = new ClassToResolve(
            new List<CollectionItem>()
                {
                    new CollectionItem(),
                    new CollectionItem(),
                    new CollectionItem()
                }

            );

Now I resolve it in a way

var classToResolve = new ClassToResolve(
            new List<CollectionItem>()
                {
                    unity.Resolve<CollectionItem>(),
                    unity.Resolve<CollectionItem>(),
                    unity.Resolve<CollectionItem>()
                }
            );

Is there a way to resolve ClassToResolve with Unity using dynamic registration?

Answer

Steven picture Steven · Jun 11, 2011

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

container.RegisterType<CollectionItem, CollectionItemA>("a");
container.RegisterType<CollectionItem, CollectionItemB>("b");
container.RegisterType<CollectionItem, CollectionItemC>("c");
container.RegisterType<CollectionItem, CollectionItemD>("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<ClassToResolve>();

If you rather inject List<CollectionItem> you can add the following registration:

container.RegisterType<IList<CollectionItem>, CollectionItem[]>();

And for IEnumerable<CollectionItem> you can add the following line:

container
  .RegisterType<IEnumerable<CollectionItem>, CollectionItem[]>();