Dependency Injection on Node.JS

Sérgio Marcelino
2 min readNov 16, 2014

I've been working with Node.JS for a while and one of the things I loved about this platform is the NPM (Node Package Manager), which allows you to manage dependencies between modules.

But it's very annoying when you have to manage the modules inside the project, things like require(‘../../foo’) are a pain and break the Dependency Injection premises.

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. (AngularJS)

I think that the fact of component knowing where the dependencies are in a filesystem aspect is an anti-pattern. So it's very important to have a library that manages all modules inside a project, the dependency injection becomes transparent and easy to plug other dependencies without the need to change existing codes, making it easier to develop Unit Tests.

Another thing I didn't like much about Node.JS is that, for every new module I create, I had to put a require on the main module or somewhere else, for example Express' Routers.

For this reason I decided to develop a lightweight Module that handles Module Loading and automatically inject dependencies when the modules are loaded.

The Acqua Module

The Acqua Module is a lightweight module loader and is also a container for Dependency Injection. It can be found on NPM or GitHub.

All you have to do is:

var acqua = new Acqua({ // new Acqua();
log : console.log, // used to log module imports, optional
err : console.err // used to log errors on module imports, optional
});

acqua.loadDir(__dirname + '/models');
acqua.loadDir(__dirname + '/services');
acqua.loadDir(__dirname + '/routers');

Inside every module the structure must be this:

module.exports = function ModuleName (dependencies, by, name) {
this.myFunction = function () {
// function implementation
};
return this;
};

It is also possible to add custom variables to the acqua’s context, just like this:

acqua.add(‘myStringVar’, ‘myValue’);
acqua.add(‘myIntegerVar’, 10);
acqua.add(‘app’, app);

And then use them everywhere, they are automatically injected:

module.exports = function (myStringVar, myIntegerVar, app) {
console.log(myStringVar, myIntegerVar);
};

Conclusion

After I developed this module I've been working with it in a couple modules and I'm very satisfied, it has never been so simple to manage dependencies without a single require on most modules.

If you have and doubt or suggestion, you're welcome to comment.

--

--

Sérgio Marcelino

Computer's Science Graduated, passionate for development in Node.JS