首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不可逆:不可注入的反向参数

不可逆:不可注入的反向参数
EN

Stack Overflow用户
提问于 2017-04-02 06:35:32
回答 1查看 1.9K关注 0票数 2

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

代码语言:javascript
复制
export interface Multiplayer{
    game: Game
    start()
}
export class WebSocketMultiplayer implements Multiplayer{
    constructor(public game: Game){}
    start(){}
}

反版本配置:

代码语言:javascript
复制
container.bind<Game>('Game').to(BasicGame)
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer)

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

代码语言:javascript
复制
const game = kernel.get<Game>('Game')
game.run()
const multiplayer = kernel.get<Multiplayer>('Multiplayer')
multiplayer.start()

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

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

代码语言:javascript
复制
start(game: Game){
        this.game = game
}

但是,它应该如何处理倒装呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-02 23:11:36

你可以尝试一些事情。

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

代码语言:javascript
复制
container.bind<Game>('Game').to(BasicGame).inSingletonScope();

您可以了解更多关于范围这里的知识。

第二个选择是使用工厂:

代码语言:javascript
复制
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 提供程序)。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43165335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档