A question that frequently rises when building enterprise applications is: “Where should we compose object graphs?” and the answer is given by the Composition Root pattern: “As close as possible to the applications entry point.”
The Composition Root pattern is described in the excellent book, Dependency Injection in .NET by Mark Seemann.
Here is the definition from the book:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
When working with the Enterprise Library, it is very common to hide the complexities of initial context creation by using the built-in IServiceLocator implementation provided by the EnterpriseLibraryContainer class.
Since I completely agree with the statement “Service Locator is an Anti-Pattern” I would like to compose all Enterprise Library modules in the Composition Root. Then, I can use well-known DI patterns (such as Constructor Injection) to supply the Dependencies.
Fortunately, the EnterpriseLibraryContainer class contains a method named “ConfigureContainer” that reads the current configuration and supplies the corresponding type information to configure a dependency injection container (by default Unity).
var configurator = new UnityContainerConfigurator(container); var configSource = ConfigurationSourceFactory.Create(); EnterpriseLibraryContainer.ConfigureContainer(configurator, configSource);
After configuring the container in the Composition Root we can resolve any instance of a type from Enterprise Library as with any other object.