Skip to main content
Version: Next

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: ResolutionContext, 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

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 from the root container down through descendant containers, so a parent container's handlers run before a child container's handlers.