Question

I'm trying to understand what CompositionRoot is about.

Right up to now I never found a deep description of what it is about, only short statements of what shall not be done.

Is the Bootstrapper that comes along when leveraging caliburn.micro already that what is meant "CompositionRoot"?

Or is it closer to the servicelocator antipattern, as it can deliver merely anything that is inside the assembly and it's dependencies.

If someone has a good description of CompositionRoot, please share. I already know the ploeh blog.

If I see that CompositionRoot leads to better architecture and / or helps me solve problems, I'm still willing to buy the book. But right know there is not enough information around for me to see what it will help.

update

Let's pretend that all of my ViewModels get an EventAggregator injected (constructor injection). Now I want to dynamically create those ViewModels when they are needed. I can register types beforehand (in the CompositionRoot), but how would I resolve dependencies later? As far as I understand, the Container should not be touched after the composition root. Definitly I do not want to create all instances before I need them (that would make the application start slow). Is "Register - Resolve - Release" meant here? (that pattern is coined in the ploeh blog, too)

Was it helpful?

Solution

I assume you've seen Mark's article at http://blog.ploeh.dk/2011/07/28/CompositionRoot.

As it states:

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

And that this should be:

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

In the case of Caliburn.Micro, the Bootstrapper class provides a ConfigureContainer method for you to override and compose you modules.

Ideally, it will only be your composition root that has a reference to your IoC container.

Caliburn.Micro will resolve your shell view model (if you use the generic version of the Bootstrapper) via your container.

It does also supply a static IoC class which is an implementation of the Service Locator (anti) pattern if you do need to reference the container outside of your composition root.

Update

If you wish to resolve types via your container at runtime after your composition root (for example if you have complex dependency chains) then use factory types.

These factory types would also have a reference to your IoC container. You could either:

  1. Pass a reference to your container as a dependency to the factory type
  2. Use the Service Locator pattern in your factories (e.g. the Caliburn.Micro IoC class)
  3. Some IoC containers such as Castle Windsor and (using an extension) Ninject will generate factory types for you based on a factory interface and conventions (this is the nicest option)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top