我怎样才能解决Funq的IoC循环依赖?
问题描述:
我有两个班,我需要互相引用。
I have two classes which I need to reference each other.
class Foo
{
public Foo(IBar bar) {}
}
class Bar
{
public Bar(IFoo foo) {}
}
当我做的:
container.RegisterAutoWiredAs<Foo, IFoo>();
container.RegisterAutoWiredAs<Bar, IBar>();
当我尝试解决任何接口,我得到一个圆形的依赖关系图这会导致一个无限循环。有没有一种简单的方法来解决这个在Funq或你知道一种解决方法吗?
and when I try to resolve either interface I get a circular dependency graph which results in an infinite loop. Is there an easy way to solve this in Funq or do you know of a workaround?
答
您可以随时(在所有集装箱,我会说)依靠懒作为依赖,而不是,这将产生预期的结果。在Funq:
You can always (and in all containers, I'd say) rely on Lazy as a dependency instead, and that would yield the desired result. In Funq:
public Bar(Lazy<IFoo> foo) ...
public Foo(Lazy<IBar> bar) ...
container.Register<IBar>(c => new Bar(c.LazyResolve<IFoo>());
container.Register<IFoo>(c => new Foo(c.LazyResolve<IBar>());