Skip to main content

How to avoid circular dependencies?

Circular dependencies occur when two classes depend on each other directly or indirectly: A imports B, and B imports A back.

You can avoid them like this:

  1. Split responsibilities. If two services know too much about each other, their logic is tangled. Move the shared part into a separate layer or service.
  2. Introduce an abstraction. One of the classes should depend not on a concrete implementation but on an interface or a token (InjectionToken).
  3. Defer the reference. Sometimes Injector or forwardRef() is enough: it lets you declare the dependency later without breaking the load order.
  4. Reconsider the architecture. If the cycle still cannot be broken, the coupling is logical, not technical, and the structure needs rethinking.

Essentially, the goal is for dependencies to flow in one direction, not loop back.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.