反转:不可注入的委托人参数

inversify: not injectable contrustor arguments

我有一个游戏 class 和一个多人游戏 class,它们处理定义游戏的所有网络玩家内容:

export interface Multiplayer{
    game: Game
    start()
}
export class WebSocketMultiplayer implements Multiplayer{
    constructor(public game: Game){}
    start(){}
}

反转配置:

container.bind<Game>('Game').to(BasicGame)
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer)

现在我想创建、配置和 运行 游戏,然后是 运行 多人游戏。

const game = kernel.get<Game>('Game')
game.run()
const multiplayer = kernel.get<Multiplayer>('Multiplayer')
multiplayer.start()

但是我应该如何将游戏实例传递给 Multiplayer 构造函数? 如果我将在 WebSocketMultiplayer 构造函数中使用 @inject,那么它将创建另一个游戏实例。

我目前使用的临时解决方案是在多人游戏开始函数中传递游戏实例

start(game: Game){
        this.game = game
}

但是 Inversify 应该如何完成?

你可以尝试一些事情。

第一个选项是使用inSingletonScope方法:

container.bind<Game>('Game').to(BasicGame).inSingletonScope();

您可以了解有关范围的更多信息 here

第二个选项是使用工厂:

container.bind<Game>('Game').to(BasicGame);
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer);

container.bind<() => Game>("GameFactory").toFactory<Game>((context: interfaces.Context) => {
    const game = context.container.get<Game>("Game");
    game.run();
    return () => game;
});

class WebSocketMultiplayer implements Multiplayer{
    public game: Game;
    constructor(@inject("GameFactory") gameFactory: () => Game){
        this.game = gameFactory();
    }
    start(){}
}

如果 game.run() 是异步的,那么您将需要一个异步工厂(又名 provider)。