停用
每当单例作用域服务被解绑时,都会分发停用事件。停用处理程序接收解析值并且不返回任何内容。
interface Weapon {
damage: number;
}
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()}`);
});
await container.unbind('Weapon');
可以通过多种方式添加停用处理程序:
- 将处理程序添加到容器。
- 将处理程序添加到绑定。
- 通过 preDestroy 装饰器将处理程序添加到类。
添加到容器的处理程序是最先被解析的。添加到子容器的任何处理程序都在添加到其父容器的处理程序之前被调用。接下来调用容器中的相关绑定,最后调用 preDestroy 方法。在上面的示例中,相关绑定是绑定到未绑定的 "Destroyable" 服务标识符的那些绑定。