Dependency Injection in Node.js - 2016 edition, part 3
This is part 3 of a 3-part series on Dependency Injection in Node.
No! This can’t be the end! There must be a way!
Angular was (AFAIK) one of the first big frameworks to introduce DI to the JavaScript world. Their approach was to use the function’s string representation and extract the names of modules that were being used. At the time that was the only way to do it.
Attempts have been made at separating the DI machinery from Angular to a separate module, but the problem is most DI modules requires all your code to cater to their specific DI system. That contradicts the very idea behind DI, and should be avoided at all costs.
We want to use DI with our service and repository without modifying their code.
Enter Awilix — the DI container you deserve.
If you don’t know what a DI container is, here’s a quick explanation. The DI container’s job is to stitch things together so that you, dear developer, won’t have to. All the plumbing code above: instantiating the services and repositories, making sure that the service gets the repository instance. All of that is done by a DI container.
Awilix is such a container, and it is implemented with ES6 Proxies, which means no more string parsing of function parameters!
Update: Awilix now supports (optional) classic injection which does parse the function parameters, and the parser is not just a shoddy regex but a purpose-built parser which works pretty well.
So back to our app — let’s try stitching our system together using Awilix! We will be using Koa 2 for the web API, so lets install the modules we need.
npm install -S koa@next koa-router@next awilix awilix-koaThe awilix-koa package makes Awilix even easier to use for Koa. Alrighty, let’s start by writing our composition root.
