Unity Register two interfaces as one singleton

Viewed 19245

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..

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

Chris

6 Answers

The proper way of doing singleton with multiple interfaces is as follows:

_container.RegisterType<EventService>(TypeLifetime.Singleton); <- This could be an instance
_container.RegisterType<IEventService, EventService>();
_container.RegisterType<IOtherEventService, EventService>();

You need to register a singleton and all the mappings to it separately. Unity v6 will have a registration method to do it all at once.

InjectionFactory is now deprecated (not sure exactly when, using Unity 5.11.7). Can be done like this:

 this.Container.RegisterType<SimulationService>(new ContainerControlledLifetimeManager());
 this.Container.RegisterFactory<IContentProvider>("SimulationContentProvider", c => c.Resolve<SimulationService>());
 this.Container.RegisterFactory<ISimulationService>(c => c.Resolve<SimulationService>());
Related