1

我试图了解如何使用解决循环依赖关系,InversifyJS但我仍然遇到问题。

我有一个Leader需要 a 的类,Follower并且Follower实例必须绑定到Leader. 我正在使用lazyInjectfrominversifyJS但仍然在report()执行 follower 的功能时将leader属性视为undefined.

下面是一个演示我的问题的示例:

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());

该行:

console.log(follower.report());

抛出错误,因为follower.leaderis undefined

关于如何解决这种情况的任何建议?

4

0 回答 0