Dav*_*ers 5 .net dependency-injection unity-container service-locator
我使用Unity来管理我的应用服务器上的服务但由于某种原因我无法使用方法'GetAllInstances'来工作.奇怪的是,相同类型的'GetInstance'似乎工作正常!
这是配置:
<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>
Run Code Online (Sandbox Code Playgroud)
我的想法是,当服务器启动时,我需要能够获得所有已配置的IService实例来初始化它们.
IUnityContainer container = ConfigureUnityContainer();
UnityServiceLocator locator = new UnityServiceLocator(container);
var single = locator.GetInstance<IService>();
var all = locator.GetAllInstances<IService>().ToList();
Run Code Online (Sandbox Code Playgroud)
正如我所说,单曲作品,但得到的一切都没有回报.即使我从配置中删除IAtomCommandService映射并且只是拥有IService它仍然不起作用.关于我在哪里出错的任何想法?
Unity工作的方式是它只能接受一个给定抽象的未命名注册.IIRC,如果你为同一个接口注册另一个具体类型,第二个会覆盖第一个.
因此,使多个服务实现相同类型的唯一方法是以不同方式命名它们.尝试为每个register元素提供名称.
UnityContainer.ResolveAll将返回所请求类型的所有命名注册,但不返回未命名的注册(如果有的话).
顺便说一句,不要使用Service Locator反模式.
| 归档时间: |
|
| 查看次数: |
1786 次 |
| 最近记录: |