Search code examples
javascripttypescriptdependency-injectioninversifyjs

inversify help required and why do we need it?


Can you recommend any great learning resources on inversify in typescript?

I have looked at http://inversify.io/ and have followed the example but am not grasping how it really works or why I need it.

A great video learning resource would be great or a simple easy beginner example.

Thanks for the help.


Solution

  • The idea of Inversion Of Control, aka dependency injection is that a class hands over control (read: responsibility) for instantiating dependent instances that the class needs to the container that will provide them with these instances instead.

    So you would not do something like:

    public constructor() {
        this._katana = new Katana();
        this._shuriken = new Shuriken();
    }
    

    I am not going to give a full example, because I would basically be copy-pasting the code that they clearly share on their website in the section 'The Basics'.
    They give an example of constructor injection:

    public constructor(
        @inject(TYPES.Weapon) katana: Weapon,
        @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
    ) {
        this._katana = katana;
        this._shuriken = shuriken;
    }
    

    This is specifically useful for:

    • Testing, since the dependent object can be mocked and injected
    • Injecting dependent objects based on variable parameters.

    For example, depending on environment you may want to inject a different configuration object with different values. This is just one example.

    Constructor injection is usually preferred over property injection, as the library also seems to support this.

    Note that what is injected is an interface, not a concrete class type.
    So the class just declares that it needs an object of type Weapon / ThrowableWeapon.

    The concrete binding happens in inversify.config.ts:

    container.bind<Weapon>(TYPES.Weapon).to(Katana)
    

    So the reason why this is useful is that you have the ability to provide concrete classes at runtime. You don't need to pre-define (hardcode) them in the class.