Search code examples
node.jstypescriptlogginginversion-of-controlinversifyjs

Inversify : contextual injection with class name


I am trying to inject loggers into different classes using inversify. I want to pass the target class name to the logger to categorize it.

The problem is I can't access the target name from where i'm creating the binding:

container.bind<log4js.Logger>(Types.Logger).toDynamicValue(context => {
    let className = context....?; // Finds class name
    return log4js.getLogger(className);
});

Is there any way of doing this other than setting it once the logger is created in the object receiving the logger?

Thank you!

Antoine


Solution

  • Update:
    This new feature makes it possible to access the class name from the context. The name will be minified though. This can be solved by comparing against the class.

    container.bind<Warrior>(TYPE.Warrior)to(Ninja).inActivation((context) => {
        const currentClass = context.currentRequest.bindings[0].implementationType;
        if (currentClass) {
            if (currentClass === Ninja) {
                // ...
            }
        }
    

    Original post:
    Thanks for asking this question. What you are looking for it is not possible at the moment but I have created an issue in GitHub to ensure that we do something about it. You can learn more about it at https://github.com/inversify/InversifyJS/issues/576