47

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, and I want a reference to the same object if I resolve the interfaces.

2
  • OK, if this is the way to go, I just keep it. Was just interested if there was a more elegant way, but it is working, and thats the point. I really like Unity so far... pretty nice in combination with PRISM Commented Sep 9, 2009 at 21:40
  • Have a look at Sven's answer... it has a lot of merit. Check out the comments by @Chris Tavares on my answer for some details. Check it out and if you like it, I'd urge you to mark that one as the answer for other people. Commented Aug 26, 2010 at 22:32

6 Answers 6

65

[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<IEventService, EventService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IEventServiceInformation, EventService>(new ContainerControlledLifetimeManager());
bool singleton = ReferenceEquals(_container.Resolve<IEventService>(), _container.Resolve<IEventServiceInformation>());

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<EventService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IEventService, EventService>();
_container.RegisterType<IEventServiceInformation, EventService>();

bool singleton = ReferenceEquals(_container.Resolve<IEventService>(), _container.Resolve<IEventServiceInformation>());
9
  • 8
    Interestingly, (at least here) it seems that when setting one of those to be a named registration it doesn't work...
    – Reddog
    Commented Jun 13, 2013 at 7:10
  • 1
    Yes, using a named registration doesn't seem to work and unfortunately that's exactly what I need. Commented Jan 31, 2015 at 0:05
  • 2
    I followed your edited answer for Unity 5.10 and it turned out not to be singleton. So this answer might be out of date unless I did something wrong.
    – grek40
    Commented May 16, 2019 at 14:35
  • 1
    @grek40 Indeed, this is a breaking change in Unity 5.2.1 as per github.com/unitycontainer/unity/wiki. Starting with that version, the [Original answer] is your friend again ;) Commented May 17, 2019 at 16:41
  • 1
    @SvenKünzler Can you add a second edit to clarify this change? Right now, it is a bit misleading and people will keep doing it wrong like I did at first.
    – Jannik
    Commented May 18, 2019 at 8:23
18

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<EventService>();
_container.RegisterInstance<IEventService>(es);
_container.RegisterInstance<IEventServiceInformation>(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<EventService>. 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

7
  • 7
    It is good practice with dependency injection, to separate wiring time from resolution time as much as possible. This solution has the drawback is that it requires you to mix calls to 'resolve' with calls to 'register' Commented Feb 22, 2010 at 2:11
  • @Nigel Thorne: Generally that is true, but in this case the OP had a service he/she needed to register that had a lot of dependencies. I suggested Unity to create this object so that those dependencies were automatically resolved so that the instance could be used for both Register calls (he/she needed the very same instance returned for either interface). Normally this is undesirable, but really the only way to do this in this case (other than instantiating the object manually). Commented Feb 22, 2010 at 12:41
  • 3
    This is really not the way to go - use Sven Kunzler's answer below instead. Commented Aug 24, 2010 at 0:16
  • 7
    @Anderson - well, this approach does work, but it has two undesirable side effects. First, two RegisterInstance calls result in two lifetime managers, which means that Dispose will be called twice on the object. That may or may not be a problem depending on the type. The other issue is this: what if EventService itself has dependencies? In that case, you can't do the Resolve call until after you're sure all EventService's dependencies are registered in the container. With the RegisterType approach, you can register it whenever you want. Commented Aug 24, 2010 at 20:43
  • 1
    @Chris Tavares: I've updated my answer to refer to Sven's as the preferred answer. Thanks for taking the time to comment on this. Lots of people will benefit from reading this. Commented Aug 26, 2010 at 22:33
7

The adaptor approach seemed to bulky for such a simple thing so I looked a bit further. To get around the problem with the named instances you need to register the type, and register factories for the interfaces.

 InjectionFactory factory = new InjectionFactory(x => x.Resolve<SimulationService>());
 this.Container.RegisterType<SimulationService>(new ContainerControlledLifetimeManager());
 this.Container.RegisterType<IContentProvider>("SimulationContentProvider", factory);
 this.Container.RegisterType<ISimulationService>(factory);

This way you do not need to create an instance of the concrete class (at registration) which was not possible in my case due to missing dependencies.

1
  • This seems like it's the correct answer. I didn't like the idea that the other solutions rely on resolving a concrete instance of the class during registration, and this avoids that. I wish Unity had some better documentation around these more "complex" uses. Commented Apr 3, 2018 at 14:38
2

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.

0

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<T> : 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<EventService>(new ContainerControlledLifetimeManager())
    .RegisterType<IEventService, EventServiceAdapter<EventService>>("namedEventService");

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

0

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>());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.