我需要弄清楚如何将接口的实现注入自身。如下面的示例所示,我想递归使用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;
}
}
这是一个递归示例,将不起作用,它返回错误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;
}
}
答案 0 :(得分:0)
结果证明,懒惰解决方案可以解决此问题,其他解决方案仍然很有趣,因为这显然是激活问题。
与懒惰一起工作的版本
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;
}
}