seesharper/LightInject

Cloned Container behaves different to container constructed with new

mirkomaty opened this issue · 0 comments

Hello everyone,

I observe a strange behavior with using LightInject 6.4.1.

I have the following TestClasses:


public class Driver
{
    private ICar _car = null;

    public Driver( ICar car )
    {
        _car = car;
    }

    // This constructor makes the difference
    public Driver(string s)
    {
        Console.WriteLine( s );
    }

    public string RunCar()
    {
        var miles = _car.Run();
        var unit = miles == 1 ? "mile" : "miles";
        return $"Running {_car.GetType().Name} - {miles} {unit}";
    }
}

public interface ICar
{
    int Run();
}

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

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

I run the following test on these classes:

var scontainer = new ServiceContainer();
scontainer.Register<ICar, BMW>();
var drv2 = scontainer.Create<Driver>();

The test behaves as expected and delivers a Driver object using the correct constructor.
If I change the test to use a Clone of the container, the test fails with the message that Driver can't be resolved, because it has no resolvable constructor:

var scontainer = new ServiceContainer().Clone();
scontainer.Register<ICar, BMW>();
var drv2 = scontainer.Create<Driver>();
   System.InvalidOperationException : Unable to resolve type: NdoDllUnitTests.Driver, service name: 
      ----> System.InvalidOperationException : No resolvable constructor found for Type: NdoDllUnitTests.Driver

If I remove the constructor with the string parameter from the class Driver, the second test passes. The clone seems to lose the ability to resolve a constructor, if more than one constructor is given.