Bi-directional dependency relationship detected! Check the StructureMap

Auto Hide Label in WPF with C#
4.9
(10)

Bi-directional dependency relationship detected! Check the StructureMap

You might be facing an issue with the circular or Bi-directional dependency in structuremap, while working with the Dependency Injection in C#. This blog post contains a solution for the Run-time exception: Bi-directional dependency relationship detected! Check the StructureMap stacktrace below…

Dependency Injection (DI) is a software design pattern. It allows us to develop loosely coupled code. The intent of Dependency Injection is to make code maintainable. Dependency Injection helps to reduce the tight coupling among software components. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.

Circular or Bi-directional dependency means Class A relies on class B in its constructor, and class B relies on class A in its constructor. If you are using structuremap to resolve your dependency then StructureMap can handle a bi-directional situation with a workaround using Lazy resolution.

Lazy Resolution – StructureMap

Here is the example of Class A and Class B. To avoid bi-direction dependency relationship exception, you can implement lazy loading as below.

public class ClassA : IClassA
{
    private readonly Lazy<IClassB> _classB;

    public ClassA(Lazy<IClassB> classB)
    {
        _classB = classB;
    }

    public IClassB ClassB => _classB.Value;
    public void ClassAMethod()
    {
       ClassB.ClassBMethod();
    }
}

public class ClassB : IClassB
{
    public IClassA _classA { get; set; }

    public ClassB (IClassA classA)
    {
        _classA = classA;
    }
    public void ClassBMethod()
    {
       //Some Code here
    }
}

Now you might have question that how to resolve the Lazy loading dependency of Interface IClassB? If you are using StructureMap ObjectFactory Class then below implementation helps you.

ObjectFactory.Configure(x => x.For<IClassA>().Singleton().Use<ClassA>());
ObjectFactory.Configure(x => x.For<Lazy<IClassB>>().Use(y => new Lazy<IClassB>(y.GetInstance<ClassB>)));

Here is the code to call ClassA and ClassB methods.

var objA = ObjectFactory.GetInstance<IClassA>();
var objB = ObjectFactory.GetInstance<IClassB>();

objA.ClassAMethod();
objB.ClassBMethod();

Please note your StructureMap implementation might different than this so please do accordingly. Read more about Lazy Resolution => https://structuremap.github.io/the-container/lazy-resolution

How useful was this post?

Click on a star to rate it!

Average rating 4.9 / 5. Vote count: 10

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?