Search code examples
c#dependency-injectioninversion-of-controllight-inject

StackOverflow exception when using Fallback with Create in LightInject 3.0.2.5


This is a copy of https://github.com/seesharper/LightInject/issues/173

I tried to automatically create concrete types using fallback and .Create() but it somehow loops itself and I don't understand why.

Here is my test code:

public class Foo
{
    public Foo(IBar bar, IBar2 bar2)
    {

    }
}

public interface IBar2
{
}

class Bar2 : IBar2
{
}

public interface IBar
{
}

class Bar : IBar
{
}

private ServiceContainer container = new ServiceContainer();


container.RegisterFallback((t, s) => true, Factory);
container.Register<IBar, Bar>();
container.Register<IBar2, Bar2>();
var foo = container.GetInstance<Foo>(); // Error here

private object Factory(ServiceRequest req)
{
    return container.Create(req.ServiceType);
}

Could you please advise?

It loops even if the Factory method looks like this:

private object Factory(ServiceRequest req)
{
    container.Register(typeof(Foo));
    return container.GetInstance<Foo>();
}

but works perfectly if I register Foo beforehand (which I obviously want to avoid)

container.Register(typeof(Foo));
var foo = container.GetInstance<Foo>(); //ok

Solution

  • I am the author of LightInject and the issue has been updated with a workaround that enables the container to resolve unregistered concrete classes.

    https://github.com/seesharper/LightInject/issues/173