How to solve circular reference?

In most cases when I’ve had to have two things reference each other, I’ve created an interface to remove the circular reference. For example:

BEFORE

public class Foo
{
    Bar myBar;
}

public class Bar
{
    Foo myFoo;
}

Dependency graph:

Foo     Bar
 ^       ^
 |       |
Bar     Foo

Foo depends on Bar, but Bar also depends on Foo. If they are in separate assemblies, you will have problems building, particularly if you do a clean rebuild.

AFTER

public interface IBar
{
}

public class Foo
{
    IBar myBar;
}

public class Bar : IBar
{
    Foo myFoo;
}

Dependency graph:

Foo, IBar     IBar
    ^          ^
    |          |
   Bar        Foo

Both Foo and Bar depend on IBar. There is no circular dependency, and if IBar is placed in its own assembly, Foo and Bar being in separate assemblies will no longer be an issue.

Leave a Comment