Unity IoC resolves and introduces a set of classes that implement a common interface

I have several classes that implement the same interface, registered under different names. I want to inject them as a collection into a constructor that unity does not 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 to insert 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 a collection of two classes (A1, A1), but class B is not generated.

Is additional configuration required?

+3


source to share


1 answer


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())));

      

+2


source







All Articles