Monday, August 29, 2005 - Posts

Dependency Injection in the Enterprise Library for .NET 2.0

The complexity of configuration has been one of the strongest cases against the Enterprise Library, some people even went to the extent of arguing that using Enterprise Library was a shortcut into XML-hell, and that Enterprise Library could easily suffer the same fate as Enterprise Java Beans (EJBs) because of this. In the last couple of years EJBs have gotten heavy competition from light-weight frameworks such as Spring and Pico Container. All these frameworks have one thing in common; they’re based around the Dependency Injection pattern. This pattern is one of the most commonly used when I help clients loosen up their architectures and create more flexible business applications. A typical usage is to combine the pattern with a service factory to hide the actual service implementation and make it easy to swap a service for another. A typical scenario would be to swap a remoting-based service for a web service, or a data access object for a mock.

Spring.NET is the richest Dependency Injection based framework for the .NET-platform, but although its sister framework for the Java platform has had huge success, our community seems to be a bit more reluctant to adopt open source frameworks, hence the Spring.NET framework isn’t as widely used. It is therefore delightful to see that the Enterprise Library makes heavy use of Dependency Injection to simplify configuration. Combined with the improved functionality in System.Configuration in .NET 2.0, Enterprise Library for .NET 2.0’s Dependency Injection features makes configuration much more transparent. Hopefully this will make more organizations adopt Enterprise Library as a common platform, instead of rolling their own enterprise frameworks.

I haven’t had much time to peruse the source code for the configuration block in Enterprise Library for .NET 2.0, but at first glance it seems that only constructor injection is supported. This style of dependency injection is the most explicit, since the object’s constructor is self-documenting regarding which arguments should be passed to configure it. A short coming of this technique is that you might have to add constructor overloads to existing objects to make them configurable. In such scenarios setter-based injection might be a better approach. This might be a bit optimistic, but I hope to see setter-based injection added to the framework before its final release.