Containerisation and Dependency Injection (IOC) in Nodejs using Awilix

Kartik Agarwal
2 min readMar 14, 2020

One of the most challenging things about building an app in NodeJS is how to structure your app. The correct way varies for different types of apps. Even for same apps, as they grow, you might need to change the way you have structured your code.

Recently, I was exploring how to manage the growing number of dependencies in my application and upon some suggestions I decided it might be the time I start using some DI (Dependency Injection) framework in the application. Upon further research, I found “Awilix”, which is a DI library. It is quite easy to use, is well documented and provides enough features (at least the ones I needed). So here is a summary of my journey with awilix.

Awilix prvovides you the power to make containers. A container is basically a scope. You register some modules(services, config, etc) in it. Now these registered services are nothing but dependencies for each other. Here is a very simple example to get a basic idea.

// create a container
const container = awilix.createContainer({
injectionMode: awilix.InjectionMode.PROXY
})
// example config json
const config = {
server: '8.8.8.8'
}
// register config and user controller to our container
container.register({
config: awilix.asValue(config),
userController: awilix.asClass(UserController)
})

//now in user controller we can directly resolve config, without the need of importing any config file.
class UserController {
constructor({config}) {
// notice how deps are injected in constructor
this.config = config
}
}

Now imagine, being able to inject any dependency in any module of your app, just by a single line of code. This becomes truly useful when you have a lot of third party dependencies like databases, redis dbs, rabitmq, etc. It makes decoupling different modules very easy.

You can also make child containers and register or update services from them, depending on your use case.

--

--