DI and tokens02 / 13

Dependency Injection and tokens

Get a game service using a token.

A token is a key the container uses to find an object. In Block Puzzle, the command that starts a session passes the Gameplay token to getSceneService and receives the game service. These excerpts show the relevant lines from BlockPuzzleServices.ts and StartBlockPuzzleSessionCommand.ts.

// BlockPuzzleServices.ts
export class BlockPuzzleServices {
  static readonly Gameplay = DiTokens.service<BlockPuzzleGameplayService>(
    'BlockPuzzleGameplayService',
  );
}

// StartBlockPuzzleSessionCommand.ts
this.getSceneService(BlockPuzzleServices.Gameplay).startSession();
TokenBlockPuzzleServices.Gameplay
RequestgetSceneService passes the token to the container
ServiceThe command calls startSession()

Sources ↗

Block Puzzle · BlockPuzzleServices.ts↗Game service tokens.Block Puzzle · StartBlockPuzzleSessionCommand.ts↗Requesting a game service using its token.