nelly2k
nelly2k

Reputation: 811

Unity IoC resolve and inject a collection of classes implementing a common interface

I have few classes implementing the same interface, registered under different names. I want to inject them as a collection into a constructor, which unity doesn't understand.

interface IA{}
interface IB { IEnumerable<IA> As { get; set; } }
class A1 : IA{}
class A2 : IA {}

class B : IB
{
    public IEnumerable<IA> As { get; set; }
    public B(IEnumerable<IA> ass)
    {
        As = ass;
    }

    public B(IA a)
    {
        var b = 1;
    }
}

Now I want inject them

[TestMethod]
public void ResolveMultiple()
{
    var container = new UnityContainer();
    container.RegisterType<IA, A1>("A1");
    container.RegisterType<IA, A2>("A2");
    container.RegisterType<IB, B>();

    var b = container.Resolve<IB>();
    Assert.IsNotNull(b);
    Assert.IsNotNull(b.As);
    var manyAss = container.ResolveAll<IA>();
}

The last line works, so I got collection of two classes (A1, A1) , but B class is not created.

Is there any extra configuration needed?

Upvotes: 3

Views: 2184

Answers (1)

nelly2k
nelly2k

Reputation: 811

Ok, the solution is to teach unity to work with IEnumerable

_container.RegisterType(typeof(IEnumerable<>), new InjectionFactory((unityContainer, type, name) => unityContainer.ResolveAll(type.GetGenericArguments().Single())));

Upvotes: 3

Related Questions