-
-
Notifications
You must be signed in to change notification settings - Fork 724
Closed
Description
Hi,
I'm using activation handlers to provide a cross cutting logging concern like in the example below. Is there anything in the context provided to the activation handler that I can use to get a dependency and make sure it respects the scope that has been defined in the original container....using get just creates a new instance which means I'm creating 2 instances of the logger class per request.
Thanks :)
interface Katana {
use: () => void;
}
@injectable()
class Katana implements Katana {
private logger: Logger;
constructor(@inject("Logger") logger: Logger) {
this.logger = logger;
}
public use() {
this.logger.log("Used Katana!");
}
}
interface Ninja {
katana: Katana;
}
@injectable()
class Ninja implements Ninja {
public katana: Katana;
public constructor(@inject("Katana") katana: Katana) {
this.katana = katana;
}
}
@injectable()
class Logger {
private id: number;
constructor () {
this.id = Math.random();
}
log(message: string) {
console.log(this.id, message);
}
}
container.bind<Ninja>("Ninja").to(Ninja).inRequestScope();
container.bind<Logger>("Logger").to(Logger).inRequestScope();
container.bind<Katana>("Katana").to(Katana).onActivation((context, katana) => {
let handler = {
apply: function(target, thisArgument, argumentsList) {
const logger = context.container.get<Logger>("Logger")
logger.log(`Starting: ${new Date().getTime()}`);
let result = target.apply(thisArgument, argumentsList);
logger.log(`Finished: ${new Date().getTime()}`);
return result;
}
};
katana.use = new Proxy(katana.use, handler);
return katana;
});
const x = container.get<Ninja>("Ninja");
x.katana.use();
// prints 0.9743319482800241 'Starting: 1521117423975'
// prints 0.11081344599818421 'Used Katana!'
// prints 0.9743319482800241 'Finished: 1521117423991'
Metadata
Metadata
Assignees
Labels
No labels
Type
Projects
Status
Done