class circular dependency resolve with inversifyJS

877 Views Asked by At

I have tried to understand how to resolve circular dependencies using InversifyJS but I'm still having an issue.

I have a class Leader which needs to have a Follower and the Follower instance must be bound to Leader. I'm using lazyInject from inversifyJS but still when report() function of follower is executed it sees leader property as undefined.

Here's follows an example that demonstrates my problem:

import { Container, inject, injectable } from "inversify";
import "reflect-metadata";
import getDecorators from "inversify-inject-decorators";

const SYMBOLS = {
  LEADER: Symbol("LEADER"),
  FOLLOWER: Symbol("FOLLOWER"),
};

const container = new Container({
  autoBindInjectable: true,
  defaultScope: "Singleton",
});

const { lazyInject } = getDecorators(container);

@injectable()
class LeaderClass {
  @inject(SYMBOLS.FOLLOWER) follower1!: FollowerClass;
  public sn = "Ldr-" + Math.floor(Math.random() * 1000);

  public report = () => {
    console.log("Leader:", this.sn);
    console.log("Follower1: ", this.follower1.sn);
  };
}

@injectable()
class FollowerClass {
  @lazyInject(SYMBOLS.LEADER) leader!: LeaderClass;
  public sn = "Flw-" + Math.floor(Math.random() * 1000);

  public report = () => {
    console.log("Follower:", this.sn);
    console.log("Leader:", this.leader.sn);
  };
}

container.bind<LeaderClass>(SYMBOLS.LEADER).to(LeaderClass);
container.bind<FollowerClass>(SYMBOLS.FOLLOWER).to(FollowerClass);

const leader = container.get<LeaderClass>(SYMBOLS.LEADER);
const follower = container.get<FollowerClass>(SYMBOLS.FOLLOWER);

console.log("--------");
console.log("   ");
console.log(leader.report());
console.log(follower.report());

The line:

console.log(follower.report());

throws an error because follower.leader is undefined.

Any suggestions on how to solve such situations?

0

There are 0 best solutions below