2017-04-02 21 views
0

私は、ゲームのクラスと定義されたゲームのためのすべてのネットワークプレーヤーのものを扱うマルチクラスを持っている:inversify:ないの注射contrustor引数

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

inversify設定:

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で行われると仮定どのようにするのですか?

答えて

1

いくつか試してみてください。

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

あなたはスコープhereについての詳細を学ぶことができます。

最初のオプションはinSingletonScopeメソッドを使用することです。

2番目のオプションは、工場を使用することです:

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 provider)が必要になります。

+0

カスタムプロミスライブラリで 'toProvider'を使う機会はありますか、それともネイティブな約束が必要なのでしょうか? – SET