Unity将两个接口注册为一个单例

我如何注册两个不同的接口在同一个实例的Unity …目前我正在使用

_container.RegisterType<EventService, EventService>(new ContainerControlledLifetimeManager()); _container.RegisterInstance<IEventService>(_container.Resolve<EventService>()); _container.RegisterInstance<IEventServiceInformation>(_container.Resolve<EventService>()); 

哪个工作,但不好看..

所以,我想你明白了。 EventService实现了两个接口,如果我parsing了接口,我想要引用同一个对象。

克里斯

编辑

在评论中得到一些反馈之后,我决定Sven的答案是一个非常优秀的答案。 感谢Chris Tavares指出技术上的优点。


这几乎是唯一的方法来做到这一点。

你可以稍微修改它(我讨厌RegisterType与每个generics参数相同的types):

 EventService es = _container.Resolve<EventService>(); _container.RegisterInstance<IEventService>(es); _container.RegisterInstance<IEventServiceInformation>(es); 

如果您的一个或多个IoC EventService要请求具体的EventServicetypes(希望不是),则需要再添加一个RegisterInstance<EventService>types的RegisterInstance<EventService> 。 希望你不需要,所有的依赖对象都是要求一个IEventService ,而不是一个EventService

希望这有助于安德森

[编辑]

可以在这里find通过XMLconfiguration完成这个工作的解决scheme。 基于这个答案,我会提出一个简化的纯代码方法如下:

 _container.RegisterType<IEventService, EventService>(new ContainerControlledLifetimeManager()); _container.RegisterType<IEventServiceInformation, EventService>(new ContainerControlledLifetimeManager()); bool singleton = ReferenceEquals(_container.Resolve<IEventService>(), _container.Resolve<IEventServiceInformation>()); 

这样,EventService类本身不会被容器发布。 由于该类应该被视为一个实现细节,这是更好的方法。

[原文解答]

有点迟了答案,但应该做的伎俩:

 _container.RegisterType<EventService>(new ContainerControlledLifetimeManager()); _container.RegisterType<IEventService, EventService>(); _container.RegisterType<IEventServiceInformation, EventService>(); bool singleton = ReferenceEquals(_container.Resolve<IEventService>(), _container.Resolve<IEventServiceInformation>()); 

适配器的方法似乎体积庞大,这样一个简单的东西,所以我看起来更进一步。 为了解决命名实例的问题,您需要注册types,并为接口注册工厂。

  InjectionFactory factory = new InjectionFactory(x => x.Resolve<SimulationService>()); this.Container.RegisterType<SimulationService>(new ContainerControlledLifetimeManager()); this.Container.RegisterType<IContentProvider>("SimulationContentProvider", factory); this.Container.RegisterType<ISimulationService>(factory); 

这样你就不需要创build具体类的实例(在注册时),由于缺less依赖关系,这在我的情况下是不可能的。

也可以为命名实例工作的一个解决scheme是使用适配器模式来创build一次性的适配器到环绕单例实例的接口。 然后解决的实例将始终被定向到单例实例,事件如果使用ResolveAll解决。 这有助于实现像IStartable之类的通用接口的一堆服务。

 public class EventServiceAdapter<T> : IEventService where T : IEventService { private readonly T _adapted; EventServiceAdapter(T adapted) { _adapted = adapted; } public string SomeMethod() { return _adapted.SomeMethod(); } } 

然后在注册的单身人员types周围注册接口适配器。

 _container .RegisterType<EventService>(new ContainerControlledLifetimeManager()) .RegisterType<IEventService, EventServiceAdapter<EventService>>("namedEventService"); 

然后,您可以隐藏任何数量的接口后面的单身人士,并使用Resolve和ResolveAll工作。

Interesting Posts