开发者

Unity 'GetAllInstances' not returning anything

I'm using unity to manage my services on my app server but for some reason I can't g开发者_StackOverflow社区et 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜