Deactivation
Whenever a singleton scoped service is unbound, the deactivation event is dispatched. A deactivation handler receives a resolved value and returns nothing.
interface Weapon {
damage: number;
}
export class Katana implements Weapon {
readonly #damage: number = 10;
public get damage(): number {
return this.#damage;
}
}
const container: Container = new Container();
container.bind<Weapon>('Weapon').to(Katana).inSingletonScope();
container.get('Weapon');
container.onDeactivation('Weapon', (weapon: Weapon): void | Promise<void> => {
console.log(`Deactivating weapon with damage ${weapon.damage.toString()}`);
});
container.unbind('Weapon');
It's possible to add a deactivation handler in multiple ways
- Adding the handler to the container.
- Adding the handler to a binding.
- Adding the handler to the class through the preDestroy decorator.
Handlers added to the container are the first ones to be resolved. Any handler added to a child container is called before the ones added to their parent. Relevant bindings from the container are called next and finally the preDestroy
method is called. In the example above, relevant bindings are those bindings bound to the unbinded "Destroyable" service identifier.