Search code examples
c#cross-reference

Risk of cross-reference


I made a class that be called 'A' and that reference 'B' class In the same time, I made a class that be called 'B' and that reference 'A' class

I made two classes like below

class A
{
   private readonly B _b;
   A(B b)
   {
      _b = b;
   }
}

class B
{
   private readonly A _a;
   B(A a)
   {
      _a = a;
   }
}

But NInjection did not allow me to make like this pattern.

So, I want to know why cross-reference can't be allowed to do.

Thank you.


Solution

  • You can use property injection to get around cyclic dependency:

    class A
    {
       public B _b {get; set;}
       public void OtherMethod() {}
    }
    
    class B
    {
       B(A a)
       {
          a._b = this;
       }
    }