Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity 'GetAllInstances' not returning anything

I'm using unity to manage my services on my app server but for some reason I can't get the method 'GetAllInstances' to work. The weird thing is that 'GetInstance' for the same type seems to work fine!

Here is the config:

<alias alias="IService" type="Atom.Server.Infrastructure.Interface.Service.IService, Atom.Server.Infrastructure.Interface"/>
<alias alias="IAtomCommandService" type="Atom.CommandServer.AtomCommandService.Interface.IAtomCommandService, Atom.CommandServer.AtomCommandService.Interface"/>
<alias alias="AtomCommandService" type="Atom.CommandServer.AtomCommandService.AtomCommandService, Atom.CommandServer.AtomCommandService"/>


<register type="IService" mapTo="AtomCommandService">
    <lifetime type="Singleton"/>
</register>
<register type="IAtomCommandService" mapTo="AtomCommandService">
    <lifetime type="Singleton"/>
</register>

The idea being that when the server starts, I need to be able to get all configured instances of IService to initialise them.

    IUnityContainer container = ConfigureUnityContainer();
    UnityServiceLocator locator = new UnityServiceLocator(container);

    var single = locator.GetInstance<IService>();
    var all = locator.GetAllInstances<IService>().ToList();

As I say, the single works, but the get all returns nothing. Even if I remove the IAtomCommandService mapping from the config and just have the IService it still doesn't work. Any ideas on where I'm going wrong with this?

like image 810
David Masters Avatar asked Jan 14 '11 08:01

David Masters


1 Answers

The way Unity works is that it can only accept one unnamed registration for a given abstraction. IIRC, if you register another concrete type for the same interface, the second overwrites the first.

So the only way to have multiple services implementing the same type is to name them differently. Try providing a name for each register element.

UnityContainer.ResolveAll will return all named registrations of the requested type, but not the unnamed registration (if there's any).

BTW, don't use the Service Locator anti-pattern.

like image 80
Mark Seemann Avatar answered Sep 21 '22 21:09

Mark Seemann