In Unity there can only be one default registration (A registration without a name as in container.RegisterType<IFoo, Foo1>();
). If multiple default registrations are performed, the last one wins.
In order to register multiple implementation for the same interface, you need to assign names to those registrations:
container.RegisterType<IFoo, Foo1>("registration1");
container.RegisterType<IFoo, Foo2>("registration2");
Also, Unity only understand arrays by default. If you want to resolve as an array then you will be fine with the default behaviour. Otherwise you will need to register a mapping between the array and the collection you are interested in, like:
container.RegisterType<IEnumerable<IFoo>, IFoo[]>();
Another important note is that the default registration won't be returned when resolving a collection.
For example given:
container.RegisterType<IFoo, Foo1>();
container.RegisterType<IFoo, Foo2>("registration1");
container.RegisterType<IFoo, Foo3>("registration2");
container.RegisterType<IEnumerable<IFoo>, IFoo[]>();
If you resolve IEnumerable<IFoo>
, the result will only contain instances of Foo2
and Foo3
, but there will not be an instance of Foo1
because the default registration is not included.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…