I'm using Unity version 2.1.505.2 and seeing unexpected behaviour when registering a UnityContainer
with a default registration and a named registration (with ParameterOverride
) for the same interface type.
If I call container.Resolve<T>()
twice - once for the named registration and once for the default registration - I get the same instance back, whereas I'd expect different instances based on the two different registrations.
Here's a code example:
public interface ICage
{
IAnimal Animal { get; }
}
public class Cage : ICage
{
public IAnimal Animal { get; private set; }
public Cage(IAnimal animal) { Animal = animal; }
}
public interface IAnimal
{
string Species { get; }
}
public class Cat : IAnimal
{
public string Species { get { return "Felis catus"; } }
}
public class Dog : IAnimal
{
public string Species { get { return "Canis lupus"; } }
}
[TestClass]
public class UnityTest
{
[TestMethod]
public void MyTest()
{
var container = new UnityContainer();
// Default registrations for IAnimal and ICage
container.RegisterType<IAnimal, Cat>(new ContainerControlledLifetimeManager());
container.RegisterType<ICage, Cage>(new ContainerControlledLifetimeManager());
// Named registration "cage2" for ICage mapping to Cage with constructor parameter override
container.RegisterType<ICage>(
"cage2",
new ContainerControlledLifetimeManager(),
new InjectionFactory(c => c.Resolve<Cage>(new ParameterOverride("animal", new Dog()))));
// Resolve ICage using the named registraion "cage2"
var cage2 = container.Resolve<ICage>("cage2");
Assert.AreEqual("Canis lupus", cage2.Animal.Species); // Assert succeeds
// Resolve ICage using the default registration ???
var cage = container.Resolve<ICage>();
Assert.AreEqual("Felis catus", cage.Animal.Species); // Assert fails (Actual:<Canis lupus>)
}
}
The second assert in the test fails because cage.Animal.Species
returns "Canis lupus"
.
Am I missing something from my understanding here? How can I set things up so that the call to container.Resolve<ICage>("cage2")
returns the Cage
instance corresponding two the named registration, and the call to container.Resolve<ICage>()
returns the instance corresponding to the default registration?