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.
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)
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.
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