Skip to content

Unable to resolve from ChildContainer when using singleton #317

Description

@Josch600

We ran into a problem using Unity.Container 5.11.11 and Unity.Abstraction 5.11.7, which I could isolate to the follwing code:

namespace UnitTests
{
    using FluentAssertions;
    using Unity;
    using Unity.Lifetime;
    using Xunit;


    public interface Interface1 { }
    public interface Interface2 { }
    public interface Interface3 { }

    public class Class1 : Interface1 { }

    public class Class2 : Interface2
    {
        public Class2(Interface1 param) { }
    }

    public class Class3 : Interface3
    {
        public Class3(Interface2 param) { }
    }

    public class UnitTest1
    {
        [Fact]
        public void Resolve_Interface3FromMainContainer_GetsClass3()
        {
            var unityContainer = new UnityContainer();

            unityContainer.RegisterType<Interface1, Class1>();
            unityContainer.RegisterType<Interface2, Class2>(new SingletonLifetimeManager());
            unityContainer.RegisterType<Interface3, Class3>();

            // works fine
            unityContainer.Resolve<Interface3>().Should().BeOfType<Class3>();
        }

        [Fact]
        public void Resolve_Interface3FromChildContainer_GetsClass3()
        {
            IUnityContainer mainContainer = new UnityContainer();
            var unityContainer = mainContainer.CreateChildContainer();

            unityContainer.RegisterType<Interface1, Class1>();
            unityContainer.RegisterType<Interface2, Class2>(new SingletonLifetimeManager());
            unityContainer.RegisterType<Interface3, Class3>();

            // resolve crashes with "Resolution failed with error: No public constructor is available for type UnitTests.Interface1."
            unityContainer.Resolve<Interface3>().Should().BeOfType<Class3>();
        }
    }
}

Everything runs fine when using a directly created container (see first test) and goes wrong when using a child container (second test). Is this the intended behaviour, maybe because of the singleton or is it a bug?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions