Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resolve circular dependencies in 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) {}
}

When I do:

container.RegisterAutoWiredAs<Foo, IFoo>();
container.RegisterAutoWiredAs<Bar, IBar>();

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?

like image 754
Rickard Avatar asked Feb 19 '23 06:02

Rickard


1 Answers

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>());
like image 159
kzu Avatar answered Mar 05 '23 03:03

kzu