Have one unity registration for more than one type but only one mapto concrete class

Jun 4, 2012 at 4:33 PM

My application has unity configuration file to map each type to its implementation. But I have a class (Foo) inherits from two different interfaces (Ifoo, IFooReader). In my unity configuration file I register the object once using the type IFoo, and mapTo= Foo. This object is injected in two different classes, but one class has a property type IFoo, and the other has the property type IFooReader. I don`t want to register the object twice under different types because I need the same instance. 

What should I do to have one object registration (Foo) but inject that instance in two classes that are expecting different types(Ifoo, IFooReader)

Thanks

Mel


Jun 5, 2012 at 4:23 PM

You say you need the same instance -- do you mean you need singletons?  

If it's singletons then you should be able to do what you want using configuration:

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <container>
      <register type="IFoo" mapTo="Foo">
        <lifetime type="singleton" />
      </register>
      <register type="IFooReader" mapTo="Foo">
        <lifetime type="singleton"/>
      </register>
    </container>
  </unity>

Then separate resolves of IFoo or IFooReader should give you the same instance of Foo.  Basically this effectively causes Foo to be a singleton. 

However, if you wish to have different lifetimes for Foo then you will need to name to identify them by name.  When using the configuration the last lifetime specified for the type is used (last in wins).  So this registers Foo as Transient (since transient is the default):

    <container>
      <register type="IFoo" mapTo="Foo">
        <lifetime type="singleton" />
      </register>
      <register type="IAnotherFoo" mapTo="Foo">
      </register>
    </container>

And if the order is reversed Foo will be registered as a singleton:

    <container>
      <register type="IAnotherFoo" mapTo="Foo">
      </register>
      <register type="IFoo" mapTo="Foo">
        <lifetime type="singleton" />
      </register>
    </container>

If you want to be able to support differing lifetimes then you can use the name attribute:

    <container>
      <!-- default registration of Foo as singleton -->
      <register type="IFoo" mapTo="Foo">
        <lifetime type="singleton" />
      </register>
      <!-- IAnotherFoo is transient but must be named otherwise will change Foo registration to transient -->
      <register name="TransientFoo" type="IAnotherFoo" mapTo="Foo">
      </register>
    </container>

You can read Using a Lifetime Manager with the RegisterType Method for more information.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com