zazoomauro / node-dependency-injection

The NodeDependencyInjection component allows you to standarize and centralize the way objects are constructed in your application.
https://github.com/zazoomauro/node-dependency-injection/wiki
MIT License
281 stars 34 forks source link

Getting a string instead of the service instance #126

Closed arctouch-eltonsantana closed 5 years ago

arctouch-eltonsantana commented 5 years ago

I have something similar to the below, and my sayHi method fails with the error sayHi is not a function

export interface IMessenger{
    sayHi();
}
export class Messenger implements IMessenger {
    sayHi() {
        console.log("Hi from a container instance!!");
    }
}
export class Application {
    constructor(private messenger: IMessenger){}

    sayHi(){
        console.log(this.messenger); //result: service.messenger 
        console.log(typeof(this.messenger)); //result: string
        this.messenger.sayHi();
    }
}

And here is the container configuration:

export function boot(container = new ContainerBuilder(), env: NodeJS.ProcessEnv = process.env) : ContainerBuilder {
    container
        .register('service.messenger', Messenger);
    container
        .register('service.application', Application)
        .addArgument('service.messenger');

    container.compile();
    return container;
}

I was expecting a Messeger object instance in the Application constructor. Am I wrong about this assumption? I already tried to use the Class instead of the Interface in the constructor but it fails with the same message.

arctouch-eltonsantana commented 5 years ago

Nevermind! I just noticed that I need to register it with .addArgument(new Reference('service.messenger')). I got confused because of the example on the readme page, I think you should consider change that example to avoid this kind of mistake.