Unity Register two interfaces as one singleton

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

    One solution that can also work for named instances is to use the adapter pattern to create throwaway adapters to the interface that wrap around the singleton instances. Then resolved instances will always be directed to the singleton instance, event if they are resolved using ResolveAll. This helps when having a heap of services that implement a generic interface like IStartable or something.

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

    Then register the interface adapter around your registered singleton type.

    _container
        .RegisterType(new ContainerControlledLifetimeManager())
        .RegisterType>("namedEventService");
    

    You can then hide any singleton behind any number of interfaces, and work using both Resolve and ResolveAll.

提交回复
热议问题