2
votes

As given in another question Getting unity to resolve multiple instances of the same type

I have initialized unity container as follows.

  static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<IFoo, Foo1>("aaa");
            container.RegisterType<IFoo, Foo2>("bbb");

            // container.Resolve<IEnumerable<IFoo>>();   returns 0
            // container.ResolveAll<IFoo>(); returns 0

            Console.WriteLine(foos.Count());

            Console.ReadLine();

        }

When the unity initialize following class, it sends an array containing two elements. But the two elements are from the same class Foo1. I don't want duplicates. I need to inject all the distinct implementation of the IFoo.

  public class Test
        {
            IFoo[] _fooSet;
            public Test(IFoo[] allRegisteredInterfaces)
            {
                _fooSet = allRegisteredInterfaces;
            }

        }

For example the solution at Injecting arrays with Unity is not working, because it creates duplicates in the injected array.

How to do this? Also note that I don't want to register instance implementations. I could easily do this by registering an array of each instance of IFoo implementations. For example following solution is not valid since it register instances instead of types.

  container.RegisterInstance<IFoo[]>(new IFood[] {
                container.Resolve<Foo1>(),
                container.Resolve<Foo2>()
            });
1
I'm not able to reproduce the issue you describe. See here. I see two instances resolved, one of each registered type.TylerOhlsen
What I did was created a black console application and tried and it worked as you mentioned. This led me to investigate more into the code base and found a wrong lifetime manger.Sriwantha Attanayake

1 Answers

1
votes

I finally found the answer. It turned out there was a custom lifetime manager and it was wrongly coded. I first created a black console application and tried the unity code example and it worked. This led to the conclusion that original code base was wrong.