2

我有一个 Game 类和一个 Multiplayer 类,它们为定义的游戏处理所有网络玩家的东西:

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构造函数?如果我将@injectWebSocketMultiplayer构造函数中使用,它将创建另一个游戏实例。

我现在使用的临时解决方案是在多人启动功能中传递游戏实例

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

但是它应该如何使用 Inversify 来完成?

4

1 回答 1

3

你可以尝试一些东西。

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

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

您可以在此处了解有关范围的更多信息。

第二种选择是使用工厂:

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()是异步的,那么您将需要一个异步工厂(AKA提供者)。

于 2017-04-02T23:11:36.397 回答