5

我使用統一來管理我的應用服務器上的服務,但出於某種原因,我無法使方法'GetAllInstances'正常工作。奇怪的是,相同類型的'GetInstance'似乎工作正常!Unity'GetAllInstances'不返回任何東西

下面是配置:

<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> 

的想法是,在服務器啓動時,我需要能夠得到IService的所有配置的實例初始化它們。

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

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

正如我所說的那樣,單件作品,但得到所有返回什麼都沒有。即使我從配置中刪除了IAtomCommandService映射,並且只有IService,它仍然不起作用。任何想法,我要去哪裏錯了?

回答

8

Unity的工作方式是,它只能接受一個未命名的註冊對於給定的抽象。 IIRC,如果您爲同一接口註冊另一個具體類型,則第二個覆蓋第一個。

所以多種服務實現相同類型的唯一方法是命名它們不同。嘗試爲每個register元素提供一個名稱。

UnityContainer.ResolveAll將返回所有命名註冊的請求類型的,但不是無名註冊(如果有任何)。

順便說一句,不要使用Service Locator anti-pattern

+0

感謝馬克 - 我發現這個問題後我才意識到這一點!總是這樣! –