In this post, I am going to code up a simplistic example of dependency injection pattern to show how other frameworks out there provide their magic out of this stunning feature of the language. Let's go 😎
Alright, let's see the final code first before going to how we can achieve this style of coding
This should look very familiar to folks in Angular world where they have to use
@Inject a lot. The service instance doesn't need to instantiate all dependencies and everything just works at runtime. This is actually very simple to achieve as we could know exactly parameter types of service instance at runtime, create them, cache for singleton) and return its according instance. Let's see how Container class and custom service decorator look like xD
Firstly, container class
And custom service decorator
As we can see, the custom service decorator does nothing more than adding the service to the list of services in container service registry. Then, whenever we need to get an instance of any service, we retrieve a list of parameter types from constructor and start instantiating them before retuning its back to the original constructor. In order to keep all services single, we need to cache them in a map data structure and create / retrieve them on demand to keep memory footprint clean.
🎉🎉🎉 Be well, Be happy 🎉🎉🎉