Wednesday, October 25, 2006

Dependency Injection

Let's talk about dependency injection (DI). DI is, essentially, a design pattern that can be applied to tightly coupled systems. For example, imagine that several modules of our system use a cryptographic component. The code may look like this:

public class OrderManager
private CCryptography _Crypto;

public OrderManager()
_Crypto = new CCryptography();

Obvious drawback of this approach is that we cannot easily swap cryptographic algorithms - multiple references in the code will need to be changed. Using DI pattern, we would extract the interface of CCryptography class and delegate the creation of concrete object to an outside factory:

public class OrderManager
private ICryptography _Crypto;

public OrderManager(ICryptography crypto)
_Crypto = crypto;

This way, different kinds of cryptographic objects can be created and swapped at run-time; OrderManager class doesn't know anything about it (and doesn't need to know, either). Another important benefit is testability: we can now test OrderManager functionality without a fully-functional cryptographic component. All we need is a mock object that implements ICryptography interface and probably doesn't even encrypt/decrypt.

By moving object creation to a new entity, we can address additional issues. For example, by caching objects in a dictionary we may apply Singleton pattern and ensure that only one instance of cryptography component is created. We can also control the order in which objects are created. Thus, we complemented original DI pattern with the concept of lifetime container.

Folks at Microsoft Patterns and Practices group took the idea even further and created dependency injection container called ObjectBuilder (OB). OB uses reflection to analyze classes and automatically fulfill their dependency requests. So, as long as we explicitly expressed a dependency (by placing it into a constructor as in the above example or a property decorated by a special attribute), OB will know what to do. There is much more to OB than I just mentioned, so if you'd like to read more, here are a couple of links:

- Download Object Builder from CodePlex:
- Great tutorial by Sayed Hashimi:,guid,d05aed4f-a211-4969-893e-7ffea324a56c.aspx