I’ve been working with several clients lately to review aging .NET code bases. One common theme I run into again and again is the misuse of (or lack thereof) dependency injection.
In my most recent code review, I ran across the following code structure where a class intended to be used as a “business object” was really used as a container to hold a dozen DataAdapters with several hard-coded SQL commands:
class BusinessObject { BusinessObjectTableAdapter _businessObjectTableAdapter = null; protected BusinessObjectTableAdapter BusinessObjectAdapter { get { if (_businessObjectTableAdapter == null) { _businessObjectTableAdapter = new BusinessObjectTableAdapter(); } return _businessObjectTableAdapter; } } }
Despite the larger architectural issues with creating a class simply to store data adapters, I found a lot of unnecessary code written surrounding the creation of objects.
If we were to retain this class, an alternate implementation could leverage a dependency injection framework such as StructureMap or Ninject, resulting in a different constructor-injected BusinessObject class:
class BusinessObject { IBusinessObjectTableAdapter _adapter; BusinessObject(IBusinessObjectTableAdapter adapter) { _adapter = adapter; } }
After this change, we’ve made the purpose and dependencies of the BusinessObject class much more clear, while allowing the consumer of the class to decide upon a specific implementation of IBusinessObject, as needed. At the same time, we’ve reduced the amount of code to maintain.
1 comment for “When to Use Dependency Injection”