unity 将两个接口注册为一个单例 [英] Unity Register two interfaces as one singleton

查看:29
本文介绍了unity 将两个接口注册为一个单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how do I register two different interfaces in Unity with the same instance... Currently I am using

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

虽然有效,但看起来不太好..

which works, but does not look nice..

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

So, I think you get the idea. EventService implements two interfaces, I want a reference to the same object if I resolve the interfaces.

克里斯

推荐答案

编辑

在评论中获得一些反馈后,我认为 Sven 的答案是一个更好的答案.感谢 Chris Tavares 指出技术优点.

After some feedback in the comments I've decided that Sven's answer is a much superior answer. Thanks to Chris Tavares for pointing out the technical merits.

这几乎是唯一的方法.

你可以稍微修改一下(我讨厌每个泛型参数都使用相同类型的 RegisterType):

You could modify it slightly (I hate RegisterType with the same type for each generic parameter):

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

如果您的一个或多个 IoC 子项要请求具体的 EventService 类型(希望不是),您将再添加一个 RegisterInstance< 类型的 RegisterInstance;事件服务>.希望您不需要它,并且所有依赖对象都要求 IEventService,而不是 EventService.

If one or more of your IoC children is going to request the concrete EventService type (hopefully not) you'd add one more RegisterInstance of type RegisterInstance<EventService>. Hopefully you don't need that and all of the dependent objects are asking for an IEventService, rather than an EventService.

希望这有帮助,安德森

这篇关于unity 将两个接口注册为一个单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆