使用构造函数注入的 StructureMap 递归

StructureMap recursion using constructor injection

我需要弄清楚如何将接口的实现注入到自身中。正如下面的示例,我想递归地使用 add 方法。

带有添加功能的简单界面

public interface IRecursiveFactory
{
    int Add(int number, int max = 10);
}

注入DI容器

container.For<IRecursiveFactory>().Use<RecursiveFactory>();

这将是显而易见的实现但它不是递归的

public class RecursiveFactory : IRecursiveFactory
{
    public int Add(int number, int max = 10)
    {
        while (number < max)
        {
            number++;
            Console.WriteLine(number);
        }

        return number;
    }
}

这是一个无法运行的递归示例,它 returns 错误 Activation error occurred while trying to get an instance of type IRecursiveFactory

public class RecursiveFactory : IRecursiveFactory
{
    private readonly IRecursiveFactory _recursiveFactory;

    // Inject "self"
    public RecursiveFactory(IRecursiveFactory recursiveFactory)
    {
        _recursiveFactory = recursiveFactory;
    }

    public int Add(int number, int max = 10)
    {
        while (number < max)
        {
            // recurse
            var newNumber = number + 1;
            Console.WriteLine(newNumber);
            number = _recursiveFactory.Add(newNumber);
        }

        return number;
    }
}

Lazy Resolution 解决了这个问题,其他解决方案仍然很有趣,因为这显然是一个激活问题。

带有 Lazy 的工作版本

public class RecursiveFactory : IRecursiveFactory
{
    private readonly Lazy<IRecursiveFactory> _recursiveFactory;

    public RecursiveFactory(Lazy<IRecursiveFactory> recursiveFactory)
    {
        _recursiveFactory = recursiveFactory;
    }

    public int Add(int number, int max = 10)
    {
        while (number < max)
        {
            var newNumber = number + 1;
            Console.WriteLine(newNumber);
            number = _recursiveFactory.Value.Add(newNumber);
        }

        return number;
    }
}