8

How to do it in code is explained here: Unity Register two interfaces as one singleton

_container.RegisterType<EventService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IEventService, EventService>();
_container.RegisterType<IEventServiceInformation, EventService>();

bool singleton = ReferenceEquals(_container.Resolve<IEventService>(),   _container.Resolve<IEventServiceInformation>());

How to do it in the XML config?

Community
  • 1
  • 1
lukebuehler
  • 4,061
  • 2
  • 24
  • 28

3 Answers3

12

Personally I like to spell out namespaces and assemblies in aliases. So xml:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">

    <alias alias="Event_Interface" type="Mynamespace.IEventService, MyAssembly"/>
    <alias alias="EventService_Interface" type="Mynamespace.IEventServiceInformation, MyAssembly"/>
    <alias alias="Event_Class" type="Mynamespace.EventService, MyAssembly"/>

    <container>
      <register type="Event_Interface" mapTo="Event_Class"> 
        <lifetime type="singleton"/>
      </register>
      <register type="EventService_Interface" mapTo="Event_Class"> 
        <lifetime type="singleton"/>
      </register>
    </container>
</unity>

code:

IUnityContainer container = new UnityContainer().LoadConfiguration();
ErnieL
  • 5,773
  • 1
  • 23
  • 27
1

Interestingly enough the accepted solution didn't work for me... It would end up creating two singletons hehe, one per interface. What did the trick for me was first registering the type to have a lifetime of singleton and then adding the actual mappings without any lifetime. Like this:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">

<alias alias="Event_Interface" type="Mynamespace.IEventService, MyAssembly"/>
<alias alias="EventService_Interface" type="Mynamespace.IEventServiceInformation, MyAssembly"/>
<alias alias="Event_Class" type="Mynamespace.EventService, MyAssembly"/>

<container>
  <register type="Event_Class"> 
    <lifetime type="singleton"/>
  </register>
  <register type="Event_Interface" mapTo="Event_Class"/>
  <register type="EventService_Interface" mapTo="Event_Class"/>
</container>
juandimr
  • 96
  • 1
  • 3
0

I didn't work with configuration files for unity yet, but according to the documentation it is

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="MyApp.Implementations" />
    <assembly name="MyApp" />
    <container>
        <register type="IEventService" mapTo="EventService" />
        <register type="IEventServiceInformation" mapTo="EventService" />
    </container>
</unity>
PVitt
  • 11,500
  • 5
  • 51
  • 85