Unity - Inject different classes for the same interface

pomber picture pomber · Oct 29, 2012 · Viewed 13.8k times · Source

I have one interface: IFoo
Two classes implementing that interface: FooOne and FooTwo
And two classes ClassOne and ClassTwo receiving an IFoo parameter in the constructor.

How I configure unity so ClassOne receives a FooOne instance and ClassTwo receives a FooTwo using only one container?

I can't do it at runtime so it must be in the config file.

Answer

Sebastian Weber picture Sebastian Weber · Oct 30, 2012

Have a look at the Unity documentation.

For a more readable config file you should define type aliases for IFoo, FooOne, FooTwo, ClassOne and ClassTwo. Then you need to register the mappings from IFoo to your implementations. You need to set a name for the mappings. For the consumers of IFoo you need to register an InjectionConstructor.

Your config will look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
      Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IFoo" type="UnityConfigFile.IFoo, UnityConfigFile" />
    <alias alias="FooOne" type="UnityConfigFile.FooOne, UnityConfigFile" />
    <alias alias="FooTwo" type="UnityConfigFile.FooTwo, UnityConfigFile" />
    <alias alias="ClassOne" type="UnityConfigFile.ClassOne, UnityConfigFile" />
    <alias alias="ClassTwo" type="UnityConfigFile.ClassTwo, UnityConfigFile" />
    <container>
      <register type="IFoo" name="1" mapTo="FooOne" />
      <register type="IFoo" name="2" mapTo="FooTwo" />
      <register type="ClassOne" mapTo="ClassOne">
        <constructor>
          <param name="foo">
            <dependency type="IFoo" name="1" />
          </param>
        </constructor>
      </register>
      <register type="ClassTwo" mapTo="ClassTwo">
        <constructor>
          <param name="foo">
            <dependency type="IFoo" name="2" />
          </param>
        </constructor>
      </register>
    </container>
  </unity>
</configuration>

That's the corresponding test that shows how it works.

UnityConfigurationSection config =
  (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
IUnityContainer container = new UnityContainer();
container.LoadConfiguration(config);
ClassTwo two = container.Resolve<ClassTwo>();
Assert.IsInstanceOfType(two.Foo, typeof(FooTwo));

Update

At runtime you can do it like this

IUnityContainer container = new UnityContainer();
container.RegisterType<IFoo, FooOne>("One");
container.RegisterType<IFoo, FooTwo>("Two");
container.RegisterType<ClassOne>(new InjectionConstructor(
  new ResolvedParameter<IFoo>("One")));
container.RegisterType<ClassTwo>(new InjectionConstructor(
  new ResolvedParameter<IFoo>("Two")));