Activation
Whenever a service is resolved, the activation event is dispatched. An activation handler receives a context and a resolved value and returns the handled resolved value.
interface Weapon {
damage: number;
}
export class Katana implements Weapon {
#damage: number = 10;
public get damage(): number {
return this.#damage;
}
public improve(): void {
this.#damage += 2;
}
}
const container: Container = new Container();
container.bind<Weapon>('Weapon').to(Katana);
container.onActivation(
'Weapon',
(_context: interfaces.Context, katana: Katana): Katana | Promise<Katana> => {
katana.improve();
return katana;
},
);
// Katana.damage is 12
const katana: Weapon = container.get<Weapon>('Weapon');
There are multiple ways to provide an activation handler
- Adding the handler to the container.
- Adding the handler to the binding.
- Adding the handler to the class through the postConstruct decorator.
When multiple activation handlers are binded to a service identifier, the postConstruct
handler is called before any others. After that, the binding handler is called. Then, container handlers are called, starting at the root container and descending the descendant containers stopping at the container with the binding.