dadhi / DryIoc

DryIoc is fast, small, full-featured IoC Container for .NET
MIT License
982 stars 122 forks source link

Resolving func-wrapper when having circular-dependency throws RecursiveDependencyDetected #651

Open BinaryCraX opened 5 days ago

BinaryCraX commented 5 days ago

Resolving a service with a circular dependency from the container crashes with ContainerException (Error.RecursiveDependencyDetected) even though a func-wrapper is used. However the same code works when using a lazy-wrapper.

The documentation states that both should work (even though there is no explicit example for the func-wrapper).

Following code crashes:

using DryIoc;

namespace DryIocCircularDep
{
    public class Child
    {
        public Child(Parent parent)
        {
            Parent = parent;
        }

        public Parent Parent { get; }
    }

    public class Parent
    {
        public Parent(Func<Child> child)
        {
            Child = child;
        }

        public Func<Child> Child { get; }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            var container = new Container();
            container.Register<Child>();
            container.Register<Parent>(Reuse.Singleton);

            var parent = container.Resolve<Parent>(); // <-- crashes

            Console.WriteLine(parent.Child().Parent == parent);
        }
    }
}

As a reference, working code using lazy-wrapper:

using DryIoc;

namespace DryIocCircularDep
{
    public class Child
    {
        public Child(Parent parent)
        {
            Parent = parent;
        }

        public Parent Parent { get; }
    }

    public class Parent
    {
        public Parent(Lazy<Child> child)
        {
            Child = child;
        }

        public Lazy<Child> Child { get; }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            var container = new Container();
            container.Register<Child>();
            container.Register<Parent>(Reuse.Singleton);

            var parent = container.Resolve<Parent>(); // <-- OK

            Console.WriteLine(parent.Child.Value.Parent == parent);
        }
    }
}

DryIoc-Version: 5.4.3

dadhi commented 5 days ago

@BinaryCraX Hi, I am afraid that there is an error in this part of the documentation. Here is the correct one https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/Wrappers.md#func-of-a You may submit a PR or I will fix it myself.