Providers and lifetimes04 / 13

DI providers and object lifetimes

Decide when to create an object and when to reuse it.

For each object, we add a rule called a provider to the DI container. It specifies the token and how to get the object. The container can return a supplied value, instantiate a class, or call a factory. Registration also determines whether the container keeps the object for later requests or creates a new one each time.

For example, the game can share one progress service. If there are two counters on screen, each needs its own component to control its text.

singletonValueReturns an existing value
singletonClassCreates an object from a class once
singletonFactoryCalls the factory once
transientClassCreates an object from a class for each request
A singleton keeps the object. A transient creates a new one.

Here is the shortened component registration. di.providers.ts

group.add('BlockPuzzleScoreComponent', BlockPuzzleScoreComponent);

Register the component in ComponentsGroup under the same name as type in the JSON. A node is an element on screen, such as the text in a counter. If we attach the component to two text nodes, the SDK creates a separate component object for each.

A singleton registered globally is shared across the game. A singleton registered in a scene container is recreated each time the scene opens.

Sources ↗

Block Puzzle · di.providers.ts↗Registration of four categories in the game.