Search code examples
c#.netdependency-injectioninversion-of-controlunity-container

How to get all instances of a type by name from unity container?


I have a container with some registered instances like:

container.RegisterInstance(typeof(Interface1), "Mapping1", new Class1("1"))
         .RegisterInstance(typeof(Interface1), "Mapping1", new Class1("2"))
         .RegisterInstance(typeof(Interface1), "Mapping2", new Class1("3"))
         .RegisterInstance(typeof(Interface1), "Mapping2", new Class1("4"));

So how can I get all instances of type Interface1 named, for example, "Mapping1"? Calling code will be something like this:

var instances = container.ResolveAll<Interface1>("Mapping1");

Thank you for answering.


Solution

  • I'm not sure that registering the instances like this is going to produce the results you want. RegisterInstance registers an object as a singleton, so by definition you cannot have more than one singleton with the same name. From the example provided above, container.ResolveAll() will only return 2 instances.