What is a composition root in the context of dependency injection?
Solution 1:
The composition root is the single place in your application where the composition of the object graphs for your application take place, using the dependency injection container (although how this is done is irrelevant, it could be using a container or could be done manually using pure DI).
There should only be one place where this happens and your container should not need to be used outside of the composition root.
Quoting from one of the answers linked to below:
In practice, this means that you should configure the container at the root of your application.
- In a desktop app, that would be in the Main method (or very close to it)
- In an ASP.NET (including MVC) application, that would be in Global.asax
- In WCF, that would be in a ServiceHostFactory
- etc.
There is a good answer here which explains a bit more about this.
See also this answer.
Solution 2:
Mark Seemann wrote a great article about Composition Root design pattern.
essential points from this article are:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
Only applications should have Composition Roots. Libraries and frameworks shouldn't.
A DI Container should only be referenced from the Composition Root. All other modules should have no reference to the container.
http://blog.ploeh.dk/2011/07/28/CompositionRoot/
I wrote my own JavaScript Dependency Injection Framework called Di-Ninja with these principles in mind
https://github.com/di-ninja/di-ninja
As I know, is the only one in javascript that implement the Composition-Root design pattern and it's documentation could be another good example to demonstrate how it works.
It work with NodeJS, browser (with Webpack or UMD/AMD), and React-Native.