Skip to content

Resolving deeply (2+ levels) nested dependencies with dependencies in child container doesn't work as expected #4

Closed
@davidarkemp

Description

@davidarkemp

I have something like:

internal class Service2 : IService2
{
    public IService3 Service3 { get; private set; }

    public Service2(IService3 service3)
    {
        this.Service3 = service3;
    }
}

internal class Service3 : IService3
{
}

internal class Service4 : IService4
{
    public IService2 Service2 { get; private set; }

    public Service4(IService2 service1)
    {
        Service2 = service1;
    }
}

internal class Service5 : IService5
{
    public Service5(IService4 service4)
    {
        Service4 = service4;
    }

    public IService4 Service4 { get; private set; }
}

I register Service2, Service4 and Service5 in my main container:

container.Register<IService2, Service2>().AsMultiInstance();

container.Register<IService4, Service4>().AsMultiInstance();

container.Register<IService5, Service5>().AsMultiInstance();

Then I add an instance of Service3 (the innermost dependency) to a child container:

var child = container.GetChildContainer();

var nestedService = new Service3();
child.Register<IService3>(nestedService);

And finally try to resolve IService5 (the outermost interface) from the child container:

var service5 = child.Resolve<IService5>();

I get an exception with the following:

TinyIoC.TinyIoCResolutionException: Unable to resolve type: IService5 ---> 
    TinyIoC.TinyIoCResolutionException: Unable to resolve type: Service5 ---> 
        TinyIoC.TinyIoCResolutionException: Unable to resolve type: Service5

Having stepped through this with the debugger, it seems to change context from the child container to the parent container when trying to resolve IService4, then it no longer has access to the concrete instance of IService3.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions