In my book I describe the Composition Root pattern in chapter 3. This post serves as a summary description of the pattern.

The Constructor Injection pattern is easy to understand until a follow-up question comes up:

Where should we compose object graphs?

It's easy to understand that each class should require its dependencies through its constructor, but this pushes the responsibility of composing the classes with their dependencies to a third party. Where should that be?

It seems to me that most people are eager to compose as early as possible, but the correct answer is:

As close as possible to the application's entry point.

This place is called the Composition Root of the application and defined like this:

A Composition Root is a (preferably) unique location in an application where modules are composed together.

This means that all the application code relies solely on Constructor Injection (or other injection patterns), but is never composed. Only at the entry point of the application is the entire object graph finally composed.

The appropriate entry point depends on the framework:

  • In console applications it's the Main method
  • In ASP.NET MVC applications it's global.asax and a custom IControllerFactory
  • In WPF applications it's the Application.OnStartup method
  • In WCF it's a custom ServiceHostFactory
  • etc.

(you can read more about framework-specific Composition Roots in chapter 7 of my book.)

The Composition Root is an application infrastructure component.

Only applications should have Composition Roots. Libraries and frameworks shouldn't.

The Composition Root can be implemented with Poor Man's DI, but is also the (only) appropriate place to use a DI Container.

A DI Container should only be referenced from the Composition Root. All other modules should have no reference to the container.

Using a DI Container is often a good choice. In that case it should be applied using the Register Resolve Release pattern entirely from within the Composition Root.

Read more in Dependency Injection in .NET.


Comments

David Martin
Reading the pre-release and it's very good. As for the single composition root: what about complex apps with several deep features? These features could be considered by some to be mini-apps in and of themselves. Would it be appropriate to consider each feature to have its own composition root? I'm thinking of Unity's child containers here. Hopefully the question makes sense. As I use your book as ammo at work I come across the particular question.
2011-08-02 03:24 UTC
Each application/process requires only a single Composition Root. It doesn't matter how complex the application is.

The earlier you compose, the more you limit your options, and there's simply no reason to do that.

You may or may not find this article helpful - otherwise, please write again :)
2011-08-02 07:56 UTC
Erkan Durmaz
Hi Mark,

My question is quite parallel to David’s. How about we have a complex application that loads its modules dynamically on-demand, and these modules can consist of multiple assemblies.

For example, a client application that has a page-based navigation. Different modules can be deployed and undeployed all the time. At design-time we don’t know all the types we wanna compose and we don’t have direct reference to them.

Should we introduce some infrastructure code, like David suggested, to let the modules register their own types (e.g. services) to a child container, then we apply “resolve” on the loaded module and dispose the child container when we are done with the module?

Looking forward to the final release of your book BTW :-)

Thanks
2011-09-29 11:57 UTC
The problem with letting each module register their own types to any sort of container is that it tightly couples the modules (and any application in which you might want to use them) to a specific container. Even worse, if you ever need to consume a service provided by one module from another module, you'd have to couple these two to each other. Pretty soon, you'll end up with a tightly coupled mess.

One option is to use whichever DI Container you'd like from the Composition Root, and use its XML capabilities to configure the modules into each particular application that needs them. That's always possible, but adds some overhead, and is rarely required.

A better option is to simply drop all desired modules in an add-in folder and then use convention-based rules to scan each assembly. The most difficult part of that exercise is that you have to think explicitly about cardinality, but that's always an issue with add-in architectures. The MEF chapter of my book discusses cardinality a bit.
2011-10-03 06:18 UTC
I left your book at home, never mind it's here on my desk. I was going to ask what your composition root for asp.net webforms looked like, but here it is on pg 227.

I think I'm headed in
UI(Asp.net) depends on Presentation layer and a pure interfaces/DTOs (with any serialization attributes/methods needed). so structure/schema of the 'model' lives in that domain-schema layer. domain model depends on the domain-schema layer, but is purely behaviors (methods/logic). In this way there's a sharing of schema/dto between service layer and presentation layer, with the clean separation of all business logic and only business logic living in the domain layer.So outside of the composition root, neither the UI, presentation layer, or resource access layers (public api -> internal adapter-> individual resource) can touch the domain methods or types. Requires we define an interface for the domain model classes I think? Cross cutting-concerns would live in their own assembly.

Any thoughts?
2011-10-21 16:09 UTC
Why would your UI depend on DTOs? A Data Transfer Object plays the role of a boundary data carrier, just like View Model might do - they fit architecturally at the same place of application architecture: at the boundary. If you base your inner architecture upon DTOs you'll be headed in the direction of an Anemic Domain Model, so that doesn't sound a particularly good idea to me...
2011-10-23 09:05 UTC
I'm only up to reading mid-way through your chapter on doing it right (and jumped to the asp.net webforms composition root after reading this blog post), but here is more of my reasoning.

The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. AnemicDomain Models - Martin Fowler


It becomes a 'real' domain model when it contains all (or most) of the behaviour that makes up the business domain (note I'm emphasising business logic, not UI or other orthogonal concerns). Anemic Domain Models - Stack overflow

I don't feel that this is headed into an Anemic domain model as the domain model assembly would contain all behaviors specific to the domain.

Designs that share very little state or, even better, have no state at all tend to be less prone to hard to analyze bugs and easier to repurpose when requirements change. Blog article - makes sense but i could be missing multiple boats here.

The domain would have zero state, and would depend on interfaces not DTOs. This would make test-ability and analysis simple.

Motivation for DTOs in the interfaces layer: presentation and persistence could all share the DTOs rather than having them duplicated in either place.
Barring that perceived gain, then the shared layer across all would just be interfaces.

The UI could depend on interfaces only, but the same assembly would contain DTOs that the presentation layer and any persistence could share without having to be duplicated/rewritten. So the domain is completely persistence and presentation ignorant.
2011-10-25 00:17 UTC
It may just be that we use the terminology different, but according to Patterns of Enterprise Application Architecture "a Data Transfer Object is one of those objects our mothers told us never to write. It's often little more than a bunch of fields and the getters and setters for them."

The purpose of a DTO is "to transfer multiple items of data between two processes in a single method call." That is (I take it) not what you are attempting to do here.

Whether or not you implement the business logic in the same assembly as your DTOs has nothing to with avoiding an Anemic Domain Model. The behavior must be defined by the object that holds the data.
2011-10-25 06:46 UTC
Jordan Morris
I appreciate your exhortations to good architecture, but I am struggling to apply them in my situation.

I am writing a WPF system tray application which has a primary constraint to keep lean, especially in terms of performance and memory usage. This constraint, along with the relatively low complexity of the application, means that I cannot justify the overhead of MVVM. In the absence of a prescribed architecture for building the object graph, I could set one up 'manually' in Application.OnStartup. Presumably it would mean instantiating all the Window objects (with dependences), which are utilised from time to time by the user.

However, I have a problem with these Window instance sitting in memory, doing nothing, 90% of the time. It seems much more sensible to me to instantiate these Window objects in the events where the user asks for them. Yet, I will want to maintain the inversion of control, so how can I avoid accessing the DI container in multiple points in my app?
2013-01-12 10:09 UTC
Jordan, would the Virtual Proxy pattern be of help here?

You can use one of the solutions outlined in my recent series on Role Hints to avoid referencing a container outside of the Composition Root.
2013-01-12 21:17 UTC
Jordan Morris
Hi Mark

I wanted to post the following comment on your linked page, here
http://blog.ploeh.dk/2011/03/04/ComposeObjectGraphsWithConfidence.aspx
but I am encountering a page error on submission.

The above article suggests a great framework for delayed construction of resources, however I have a different reason for wanting this than loading an assembly.

In my scenario I have occasionally-needed Window objects with heavy GUIs, presenting lots of data. The GUI and data only need to be in memory while the Window is displayed. The lazy loading approach seems to apply, except it leaves me with a couple of questions.

1) When the window is closed again, I want to release the resources. How can I unload and reload it again?

2) What would this line look like when using an IoC like Ninject?

> new Lazy<ISolo<IMarker>>(() => new C1(

An alternative I am considering is putting classes defining events in the object graph, instead of the windows themselves. These event classes could be constructed with instances of dependencies which will be used in the event methods to construct Windows when needed. The dependancies I am wanting to inject to maintain inversion of control are light-weight objects like persistance services which will exist as singletons in memory anyway (due to the way most IoC's work). Do you see any problem with this?

Many thanks.
2013-01-13 23:07 UTC
I'll refer you to section 6.2 in my book regarding lifetime management and the closing of resources. However, if things aren't disposable, you can also just let them go out of scope again and let the garbage collector take care of cleaning up.

I can't help you with Ninject.

2013-01-18 10:03 UTC


Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or Google Plus, or somewhere else with a permalink. Ping me with the link, and I may add it as a comment.

Published

Thursday, 28 July 2011 15:22:04 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!