1

I read Dependency Injection Principles, Practices, and Patterns and I try to figured out what actually is the difference between Composition Root and Composer.

In the book their definitions are:

Composition Root is a single, logical location in an application where modules are composed together.

Composer is a unifying term to refer to any object or method that composes Dependencies. It’s an important part of the Composition Root. The Composer is often a DI Container, but it can also be any method that constructs object graphs manually (using Pure DI).

Is Composition Root more like the name of the place/location where we should create our application graph and Composer is that thing which actually does it? Or it is something else?

If you use a DI Container, the Composition Root should be the only place where you use the DI Container.

What else you possible could have in Composition Root ? Isn't it only A DI Container?

public class CompositionRoot
{        
    public static IContainer Compose()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<Calculator>().As<ICalculator>().SingleInstance();


        return builder.Build();
    }
}

Regards

chunk1ty
  • 169
  • 1
  • 10

1 Answers1

1

The Composition Root can be considered an architectural Module or even a Layer. It can have all the infrastructure required to tie the application together, which doesn't belong in any of the lower layers (e.g. presentation, domain, or data access layers). Think about code that:

  • reads from message queues and dispatches messages to the application,
  • decorators that apply cross-cutting concerns,
  • adapter implementations that connect the application with the outside world

Where the Composition Root can have all this infrastructure code, the Composer will just consist of the code that news all those pieces of code, ensures caching according to their lifestyle, and builds the object graphs out of those created components.

Steven
  • 151,500
  • 20
  • 287
  • 393
  • May we say that Composition Root is a module(in simple words the name of the file in the above example - CompositionRoot.cs ) where we have to create application graph (also here we may load some file configuration) and the Composer is that thing that actually build application graph (Compose() method in the above example) ? – chunk1ty Mar 01 '20 at 15:54
  • A *Module* is a group of related classes. A layer consists of one of more module, and a module consists of one or more classes. So implying that the composition root is a single class or file is incorrect. – Steven Mar 02 '20 at 08:19
  • The `Compose` method in your example is *not* a composer. In your case the `Compose` method is the part of the Composition Root that constructs the *composer*. In your example, the `IContainer` (built by the `ContainerBuilder`) is the Composer. – Steven Mar 02 '20 at 08:21