Search code examples
c#dependency-injectioncircular-dependency

Circular dependency on injection within same class library


I have below classes and implementation inside same class library

public interface IA
    {

    }

    public class A : IA
    {
        private IB _ib;

        public A(IB ib)
        {
            _ib = ib;
        }
    }

    public interface IB
    {

    }

    public class B : IB
    {
        private IA _ia;

        public B(IA ia)
        {
            ia = _ia;
        }
    }

My question is when, either IA or IB, gets instantiated, will it create any circular dependency when performing dependency injection? If so, how can this be resolved?


Solution

  • Your code will have circular dependency and will throw exception at runtime. You need to refactor your code so that A and B do not have dependencies on each other. You will need to extract a new interface (IC) out of either A or B and refactor your code to something like the following:

    public interface IA {
    }
    public class A : IA {
      IC _c;
      public A(IC c) {
        _c = c;
      }
    }
    
    public interface IB {
    }
    public class B : IB {
      IA _a;
      IC _c;
      public B(IA a, IC c) {
        _a = a;
        _c = c;
      }
    }
    
    public interface IC {
    }
    public class C : IC {
    }
    

    See Circular Dependency in constructors and Dependency Injection on how to refactor your classes to remove circular references