Composition Root by Mark Seemann
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
(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 Principles, Practices, and Patterns.
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 :)
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 :-)
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.
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.
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.
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.
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?
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.
I wanted to post the following comment on your linked page, here
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?
I can't help you with Ninject.
You make the point that only the composition root should register dependencies of various layers and components. And thereby only the project containing the composition root would have references to the DI container being used
In a couple of projects I've worked on we have multiple applications and thereby composition root, being websites, service endpoint, console applications etc. giving us around 10 application endpoints that needs to have their own composition roots. But at the same time we work with a components based design which nicely encapsulates different aspects of the system.
If I were to only do my registration code within the place of the composition roots, then applications using the same components would have to register exactly the same dependencies per compontent, leading to severe code duplication
At this point we've gone with a solution where every component has their own registration class which the composition root's then register, so basically out composition roots only compose another level of composition roots. I hope it makes sense!
What I'm explaining here directly violates the principles you make in this post. Which I already had I sense it would. But at the same time I don't know how else to manage this situation effectively. Do you have any ideas for how to handle this type of situation?
Allan, thank you for writing. In the end, you'll need to do what makes sense to you, and based on what you write, it may make sense to do what you do. Still, my first reaction is that I would probably tend to worry less about duplication than you seem to do. However, I don't know your particular project: neither how big your Composition Roots are, or how often they change. In other words, it's easy enough for me to say that a bit of duplication is okay, but that may not fit your reality at all.
Another point is that, in my experience at least, even if you have different applications (web sites, services, console applications, etc.) as part of the same overall system, and they share code, the way they should be composed tend to diverge the longer they live. This is reminiscent of Mathias Verraes' point that duplication may be coincidental, but that the duplicated code may deviate from each other in the future. This could also happen for such applications; e.g. at one point, you may wish to instrument some of your web site's dependencies, but not your batch job.
My best advice is to build smaller systems, in order to keep complexity down, and then build more of them, rather than building big systems. Again, that advice may not be useful in your case...
Another option, since you mention component-based design, is to move towards a convention-based approach, so that you don't have to maintain those Composition Roots at all: just drop in the binaries, and let your DI Container take care of the rest. Take a look at the Managed Extensibility Framework (MEF) for inspiration. Still, while MEF exposes some nice ideas, and is a good source of inspiration, I would personally chose to do something like this with a proper DI Container that also supports run-time Interception and programmable Pointcuts.
In the end, I think I understand your problem, but my overall reaction is that you seem to have a problem you shouldn't have, so my priority would be:
It seems that I have a certan inclination for reopening "old" posts. Still the may be considered evergreens! :) Now back on topic.
When it comes to the well known frameworks as ASP.NET MVC, Web.API, WCF, it is quite clear on where and how to set our composition root. But what if we do not have a clear "entry point" to our code? Imagine that you are writing an SDK, laying down some classes that will be used by other developers. Now, you have a class that exposes the following constructor.
public MyClass(IWhatEver whatEver)Consider also that who is going to use this classes has no idea about IWhatEver nor it should have. For make the usage of MyClass as simple as possible, we I should be able to instatiate MyClass via the parameterless constructor. I had the idea of making the constructor that is used for DI, internal, and the only publically available one to be the paramtereless constructor. Then fetch somehow the instances of my dependencies in the paramterless constructor. Now imagine that I have several of classes as MyClass and that I do have a common set of "services" that are injected inside of them. Now, my questions are.
Mario, thank you for writing. If you're writing an SDK, you are writing either a library or a framework, so the Composition Root pattern isn't appropriate (as stated above). Instead, consider the guidelines for writing DI friendly libraries or DI friendly frameworks.
So, in order to answer your specific questions:
1: Conceptually, there should only be a single Composition Root, but it belongs to the application, so as a library developer, then no: 'you' can't have any Composition Root.
2: A library shouldn't trigger any composition, but as I explain in my guidelines for writing DI friendly libraries, you can provide Facades to make the learning curve gentle. For frameworks, you may need to provide appropriate Abstract Factories.
3: The performance impact of Composition shouldn't be a major concern. However, the real problem of attempting to apply the Composition Root pattern where it doesn't apply is that it increases coupling and takes away options that the client developer may want to utilize; e.g. how can a client developer instrument a sub-graph with Decorators if that sub-graph isn't available?
4: There are better ways to design DI friendly libraries and DI friendly frameworks.
Thank you for your quick and valuable replay.
I read your posts and made some toughs about them. Still I am not convinced that what is described in that posts does tackle my problem. Even more I'm realizing that is less and less relevant to the topic of composition root. However, let me try describe a situation.
I do plan to write an SDK (a library that will allow developers to interact with my application and use some of it's functionality). Consider that I'm exposing a class called FancyCalculator. FancyCalculater needs to get some information from the settings repository. Now, I have a dependency on ISettingsRepository implementation and it is injected via a constructor into my FancyCalculator. Nevertheless, who is going to use the FancyCalculator, doesn't know and he shouldn't know anything about ISettingsRepository and it's dependency tree. He is expected only to make an instance of FancyCalculator and call a method on it. I do have a single implementation of ISettingsRepository in form of SettingsRepository class. In this case, how do I get to create an instance of SettingsRepository once my FancyCalculator is created?
A Factory? Service locator? Something else?
Composition root in applications like MVC, WebAPI, etc, is a very nice and clean approach, but what about the situations when we do not have a clean single entry point to the application?
Thank you again!
Mario, thank you for writing again. As far as I understand, you basically have this scenario:
Then you say: "a dependency on ISettingsRepository implementation and it is injected via a constructor into my FancyCalculator". Okay, that means this:
But then you say: "who is going to use the FancyCalculator, doesn't know and he shouldn't know anything about ISettingsRepository and it's dependency tree."
That sounds to me like mutually exclusive constraints. Why are you injecting ISettingsRepository into FancyCalculator if you don't want to enable the user to supply any implementation of ISettingsRepository? If you don't want to allow that, the solution is easy:
If you want the best of both worlds, the solution is the Facade pattern I already described in my DI Friendly library article.
Hi Mark, You got the example right. The reason of my choices are the following. I do not want user of my library to know about the dependencies for a couple of reason. First of all it needs to be as simple as possible to use. Second thing the dependencies are let's say "internal", so that code is loosely coupled and testable. He should not know even about them or get bothered at any point. Still I do not think it's wise to create instances of the dependencies in the parameterless constructor. Why? Well, I am concerned about maintainability. I would like a to somehow request the default instance of my dependency in the parameterless constructor and get it, so that I do have a single point in my sdk where teh default dependency is specified, and also that I do not need to handle the dependency tree. The fact is that I can't get what this something should be. I re-read the chapter 5 of your book this weekend to see if I can come up with something valid ideas. What I came up with is that I should use the parameterless constructor of each of my classes to handle it's own default dependencies. In this way, resolving the tree should be fine, and it is easy to maintain. Also to prevent user to see the constructors that to require the dependencies to be injected (and confuse it) I tough of declaring these constructors as internal. This are my words translated in code (easier to understand).
What do you think about a solution like this? What are a bad sides of this approach? Is there any pattern that encapsulates a practise like this?
Mario, you don't want the user of your library to know about the dependencies, in order to make it easy to use the SDK. That's fine: this goal is easily achieved with one of those Facade patterns I've already described. With either Constructor Chaining, or use of the Fluent Builder pattern, you can make it as easy to get started with FancyCalculator as possible: just invoke its parameterless constructor.
What then, is your motivation for wanting to make the other constructors internal? What do you gain from doing that?
Such code isn't loosely coupled, because only classes internal to the library can use those members. Thus, such a design violates the Open/Closed Principle, because these classes aren't open for extension.
I am pretty sure that Mario uses internal code in order to be able to write unit tests. Probably the interfaces of the dependecies which he is hiding should also be internal. I think it is a good aproach because thanks to it he can safely refactor those interfaces, beacuse it is not a public API and also he can have unit tests.
Yes - "Such code isn't loosely coupled, because only classes internal to the library can use those member", however I think that very often stable API is very important for libraries.
Could you give any comments on that?
Robert, thank you for writing. Your guess sounds reasonable. Even assuming that this is the case, I find it important to preface my answer with the caution that since I don't know the entire context, my answer is, at best, based on mainstream scenarios I can think of. There may be contexts where this approach is, indeed, the best solution, but in my experience, this tends not to be the case.
The .NET platform is getting much better in this regard, but it's still not nearly as good as it could be. Additionally, .NET is littered with failed technologies that turned out to be completely useless after all (Windows Workflow Foundation, Commerce Server, (early versions of) Entity Framework, etc.).
.NET has suffered from a combination of fear of breaking backwards compatibility, combined with Big Design Up-Front (BDUF). The fact that (after all) it's still quite useful is a testament to the people who originally designed it; these people were (or are) some of most skilled people in the industry. Unless you're Anders Hejlsberg, Krzysztof Cwalina, Brad Abrams, or on a similar level, you can't expect to produce a useful and stable API if you take the conservative BDUF approach.
Instead, what you can do is to use TDD to explore the design of your API. This doesn't guarantee that you'll end up with a stable API, but it does help to make the API as useful as possible.
How do you ensure stability, then? One option is to realise that you can use interfaces as access modifiers. Thus, you can publish a library that mostly contains interfaces and a few high-level classes, and then add the public implementations of those interfaces in other libraries, and clearly document that these types are not guaranteed to remain stable. This option may be useful in some contexts, but if you're really exposing an API to the wild, you probably need a more robust strategy.
The best strategy I've been able to identify so far is to realise that you can't design a stable API up front. You will make mistakes, and you will need to deal with these design mistakes. One really effective strategy is to apply the Strangler pattern: leave the design mistakes in, but add new, better APIs as you learn; SOLID is append-only. In my Encapsulation and SOLID Pluralsight course, I discuss this particular problem and approach in the Append-Only section of the Liskov Substitution Principle module.
Good point Mark! I really like your point of view, in general I agree with you.
I will try to 'defend' the internal dependecies, beacuse it may help us explore all the possible reasonable usages of it.
1. Personlly I would hide my dependencies with internal access when I would be quite certain that my design is bad, but I do not have time to fix it, but I will do it for sure in probably near future.
2. Moreover if I would have unit tests without accessing to internal's (so not the case which I was writing in my previous comment), then I should be able to refactor the 'internals' without even touching the unit tests. This is why I see internal depedencies as a refactoring terchnique - especially when working with legacy code.
These were some cases for Library/Framework. What about internal access in non-modular Application development that is consists of several projects (dll's)? Personally I try to keep everthing internal by default and only make public interfaces, entities, messages etc. for things that are used between the projects. Then I compose them in a dedicated project (which I name Bootstrapper) which is a composition root and has access to all internal types... If your books covers this topic - please just give a reference. I have not read your book so far, but it is in the queue :)
Please note that I'm not saying that internal or private classes are always bad; all I'm saying is that unit testing internal classes (presumably using the [InternalsVisibleTo] attribute) is, in my opinion, not a good idea.
You can always come up with some edge cases against a blanket statement like never unit test internal classes, but in the general case, I believe I've already outlined why I think it's a really poor idea to do so.
Ultimately, I've never understood the need for the [InternalsVisibleTo] attribute. When you're applying it, you're basically making internal types public to select consumers, with all the coupling that implies. Why not make the types truly public then?
As far as I can tell, the main motivation for not making types public is when the creators don't trust their code. If this is the case, making things internal isn't a solution, it's a symptom. Address the problem instead of trying to hide it. Make the types trustworthy by applying encapsulation.
An example from my last days at work: I marked a class as internal that is wrapping some native library (driver for some hardware) using [DllImport]. I want clients of my Library use my classes - not the DLL wrapper - this is why I hide it using internal. However I needed InternalVisibleTo so that I could write integration tests to see if the wrapper really works.
Why making public when nobody outside is using it? YAGNI. I only expose when I know when its needed for the clients. Then for those that I have already exposed I need to have backward compability. The less I have exposed the more easily and safely I can refactor my design. And it is not about always bad design. New requirements frequently come in parallel with refactoring the design. This is why I like the Martin Fowler's idea of Published Interface which is also mentioned in his Access Modifier article.
Additionally I always had a feeling that making everything public can affect badly influence the software architecture. The more encaupsulated are the packages the better. And for me internal access is also a mean of encaupsulation at the packaging level. Three days ago Simon Brown had a presentation named "Software Architecture vs Code" on DevDay conference. When he told something like "do not make public classes by default" people were applauding!
My rules of a thumb for seting the class access modifiers are:
Thank to Mark Seemann for his very inspiring write about Composition Root design pattern, /2011/07/28/CompositionRoot/
It work for both NodeJS and browser (with Webpack)
Thanks for this insightful post!
I was just wondering, could we say then that using a Service Locator exclusively at the Composition root is not something bad, actually is perfectly fine?
I'm asking this, since it's wide-spread the service locator 'anti-pattern', however, at the Composition root its usage is not a problem at all, right ?
Thanks for the amazing blog! ;)
Lisber, thank you for writing. Does this answer your question?
The sum up at the end of that article is brilliant!It becomes a Service Locator if used incorrectly: when application code (as opposed to infrastructure code) actively queries a service in order to be provided with required dependencies, then it has become a Service Locator.
Thank you for clarifying that.