Unity Register two interfaces as one singleton

前端 未结 5 602
悲&欢浪女
悲&欢浪女 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:28

    [2nd Edit]

    Because of breaking changes in the way Unity handles registrations, the updated approach does not work anymore. The [Original answer] is the way to go again. (For more details about the changes in Unity, please refer to the link given in the comments below.)

    [Edit]

    The solution for doing this via XML configuration can be found here. Based on that answer I would propose a streamlined code-only approach as follows:

    _container.RegisterType(new ContainerControlledLifetimeManager());
    _container.RegisterType(new ContainerControlledLifetimeManager());
    bool singleton = ReferenceEquals(_container.Resolve(), _container.Resolve());
    

    This way, the EventService class itself is not published by the container. As the class should be considered an implementaion detail, this is the preferable approach.

    [Original answer]

    A little late an answer, but should do the trick:

    _container.RegisterType(new ContainerControlledLifetimeManager());
    _container.RegisterType();
    _container.RegisterType();
    
    bool singleton = ReferenceEquals(_container.Resolve(), _container.Resolve());
    

提交回复
热议问题