gpt4 book ai didi

c# - DryIoc 递归依赖异常与工厂(Func<>)

转载 作者:行者123 更新时间:2023-12-03 23:04:10 27 4
gpt4 key购买 nike

嘿,我已经从 Autofac 切换到 DryIoc。我的代码以前可以工作,但现在导致异常“解析时检测到递归依赖项”。 (代码已简化)

public class AFactory {
public AFactory(Func<A> getA){ }
}

public class BFactory {
public BFactory(Func<B> getB, AFactory factory){ }
}

public class A {
public A(IrrelevantService service, BFactory factory){ }
}
实际代码很复杂,因此假设有必要使用此代码结构。
它正在尝试解决 AFactory --> A --> BFactory --> AFactory ,这是导致问题的原因。但是因为它使用的是 Func<> 所以应该没问题吧? (或者至少它在 Autofac 中)。
有没有办法注册这个,这样它就不会抛出这个异常?

最佳答案

这是reason from the Func wrapper docs :

By default, does not permit recursive dependency.


修复在下面的文档或 later section 中进行了描述。 .
Here are all possible fixes :
using System;
using DryIoc;

public class Program
{
public static void Main()
{
var c = new Container(
//rules => rules.WithFuncAndLazyWithoutRegistration() // fix1: make everything lazy resolvable preventing the recursive dependency check!
);

c.Register<A>(
//setup: Setup.With(asResolutionCall: true) // fix2: makes A a dynamically resolvable
);
c.Register<AFactory>();

c.Register<B>();
c.Register<BFactory>(
setup: Setup.With(asResolutionCall: true) // fix3: makes BFactory a dynamically resolvable - the fix is here and not in B because the BFactory is already loops to AFactory and making B dynamic is not enough
);

c.Register<IrrelevantService>();

var af = c.Resolve<AFactory>();
Console.WriteLine(af);
}

public class AFactory {
public AFactory(Func<A> getA){ }
}

public class BFactory {
public BFactory(Func<B> getB, AFactory aFactory){ }
}

public class A {
public A(IrrelevantService service, BFactory bFactory){ }
}

public class B {}
public class IrrelevantService {}
}

关于c# - DryIoc 递归依赖异常与工厂(Func<>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63702393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com