Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 997
Thomas Avatar asked Jun 08 '11 11:06

Thomas


People also ask

What is a composition root?

What is a Composition Root? Definition. A Composition Root is a (preferably) unique location in an application where modules are composed together. Figure 1. Close to the application is entry point, the Composition Root takes care of composing object graphs of loosely coupled classes.

Is composition a dependency injection?

Dependency Injection is a Design pattern that enables us to write loosely coupled code and enforces, dependent object gives up control of managing their dependencies and instead let a Composition Root inject the dependencies into them.

What is the dependency injection concept?

In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency.


1 Answers

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.

like image 106
Sam Holder Avatar answered Sep 29 '22 10:09

Sam Holder