What is a composition root in the context of dependency injection?

后端 未结 2 1782
故里飘歌
故里飘歌 2020-11-22 07:38

I am exploring dependency injection and the term composition root is used all over the place. So what is it?

2条回答
  •  面向向阳花
    2020-11-22 08:25

    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.

提交回复
热议问题