Dependency injection is a programming technique that makes a module independent of its dependencies. This enables you to replace dependencies without changing the module that uses them.
To illustrate Dependency Injection, we’ll build an API with the following endpoints
GET /post: Gets all posts
POST /post: Creates a post
and structure the API in the following way:
Datasource — persistence implementation using third party modules.
Repository — decouple application from persistence: has a datasource dependency.
UseCase — business logic: has a repository dependency.
Presentation — routes: has a use-case dependency.
1. PostDataSource
The post datasource uses on third a party lib as shown in the require statement. (nedb is an embedded persistent database for Node. API is a subset of MongoDB)
2. PostRepository
The repository is a way of decoupling our datasource from the rest of our application. The datasource is therefore property injected into the repository. Once injected, all the functions within the repository now have access to this external dependency. This is using the closure feature within Javascript
A closure is a feature where an inner function has access to the outer (enclosing) function’s variables
3. CreatePost UseCase
As we’ve done with the post repository, the post repository is now property injected into the use-case.
Let’s now build the post router and see how we chain these dependencies.
4. Post Router
With the code above, we manually need to create and chain together the dependencies in order to produce a use-case object on which we run the execute command to produce the result the endpoint responds with.
We can simplify the process of manually managing dependencies by using an IoC container. IoC container (a.k.a. DI Container) is a framework for implementing automatic dependency injection. It manages object creation, and also injects dependencies.
Let us firstly create the container.
IoC Container
All dependencies are imported and registered here. We use the Awilix third party library to help use create the container
Let’s now revisit our router and replace manually dependency management with the use of the container.
Post Router with Container
And that’s it. We’ve now shown how we can use dependency injection in Javascript and without classes.