July 10th, 2018
Seamless Injection — A Better Way of Managing Dependencies in Node.js
There are a lot dependency injection frameworks which help with managing dependencies and help us to implement testable code and dependency inversion principle from SOLID. However, those frameworks are not flexible enough and there are coupling between classes and container. In other words, we are still injecting our class directly inside other class when resolving dependencies and we depend on container.
Another approach that I came up with is to let details depend on events. That way we have lower level coupling because we require some dependency only when we need it. In other words, we will get it whenever we call a specific event. Also, we do not need to inject classes into each other.
This is how these two different approaches look like:
For dependency injection we see the main code depends on dep1 and dep1 depends on dep2 and dep2 depends on dep3 and so on. On the other hand, when it comes to seamless injection we can call any dependency whenever and wherever we want because we don’t need to know the specific location of that dependency in the container. All we need to do is to call the event, which will resolve dependency for us. It is easy to unbind event and set whatever we want with this kind of approach.
Here is a repo with the code for better understanding.
This is still in experimental phase and there can be some limitations.