Unity Container returns singleton instead of new instance

Viewed 272

I am trying to figure out how Lifetime Managers work. I Registered 2 types and injected one into another(Audi into Driver). I created two Driver instances and it seems they are using the same instance of Audi, when I expected every Driver to have it's own Audi instance (since TransientLifetimeManager is being used).

    public interface ICar
    {

        int Run();
    }

    public class Audi : ICar
    {            
        private int _miles = 0;

        public int Run()
        {
            return ++_miles;
        }
    }

    public class Driver
    {
        public ICar _car = null;       
        public Driver(ICar car)
        {
            _car = car;

        }

        public void RunCar()
        {
            Console.WriteLine("Running {0} - {1} mile ", _car.GetType().Name, _car.Run());
        }
    }



container.RegisterType<ICar, BMW>();
container.RegisterType<Driver>(new InjectionConstructor(container.Resolve<ICar>()));
var driver = container.Resolve<Driver>();
var driver2 = container.Resolve<Driver>();
//False, that's fine.
Console.WriteLine(ReferenceEquals(driver,driver2));
//True. Why??
Console.WriteLine(ReferenceEquals(driver._car,driver2._car));           

//The situation changes if I don't use InjectionConstructor parameter:
 container.RegisterType<Driver>();
//Now it returns False.
Console.WriteLine(ReferenceEquals(driver._car,driver2._car));

What is difference? Why the usage of InjectionConstructor changes the behaviour?

1 Answers
Related