In my current TypeScript project utilizing inversify, I have set up a logger in my TYPES as TYPES.ILoggger
. When I access the logger directly from my container, it functions as expected:
import {ILogger} from "./interfaces/ILogger";
import {TYPES} from "./interfaces/TYPES";
import container from "./kernel/inversify.config";
const loggerFromTheContainer: ILogger = container.get<ILogger>(TYPES.ILogger);
loggerFromTheContainer.info("I WILL LOG"); // this works
Everything seems to be properly configured.
Instead of accessing the container directly, I want to implement property injection. InversifyJS' README provides an example:
You can choose to use property injection instead of constructor injection so you don't need to declare the class constructor:
@injectable() class Ninja implements Warrior { @inject(TYPES.Weapon) private _katana: Weapon; @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon; public fight() { return this._katana.hit(); } public sneak() { return this._shuriken.throw(); } }
I attempted to follow this approach for injecting the logger.
However, when I try to inject the logger via property injection, it turns out to be undefined
and I am unsure why:
@injectable()
class ShouldHaveLogger {
@inject(TYPES.ILogger) private logger: ILogger;
constructor() {
this.logger.info("Hello World"); // the logger remains undefined here
}
}
new ShouldHaveLogger();
This results in a generic
TypeError: Cannot read property 'info' of undefined
since this.logger
is not being injected. How can I resolve this issue?