Search code examples
c#ioc-containerservicestackcircular-dependencyfunq

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?


Solution

  • 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>());