I have an existing typescript project using inversify. I have defined a logger in my TYPES at TYPES.ILoggger
and when I access the logger directly from my container it works:
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
So my setup should be fine.
I don't want to access the container directly but I want to use property injection. [InversifyJS' README provides an example:
If you prefer it you can use property injection instead of constructor injection so you don't have 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(); } }
and I try to follow that one.
Yet when I try to inject the logger through property injection, I suddenly get undefined
as a logger and I don't know why:
@injectable()
class ShouldHaveLogger {
@inject(TYPES.ILogger) private logger: ILogger;
constructor() {
this.logger.info("Hello World"); // this.logger will remain undefined
}
}
new ShouldHaveLogger();
It will throw a generic
TypeError: Cannot read property 'info' of undefined
as this.logger
is not being injected. Yet why and how to fix it?