Reputation: 811
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
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