Unity Register two interfaces as one singleton

前端 未结 5 603
悲&欢浪女
悲&欢浪女 2020-12-07 17:22

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

        _container.RegisterType

        
5条回答
  •  感动是毒
    2020-12-07 18:07

    Edit

    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.


    That's pretty much the only way to do it.

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

    EventService es = _container.Resolve();
    _container.RegisterInstance(es);
    _container.RegisterInstance(es);
    

    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. Hopefully you don't need that and all of the dependent objects are asking for an IEventService, rather than an EventService.

    Hope this helps, Anderson

提交回复
热议问题