Types of Dependency Injection
There are three common forms of dependency injection:
- Constructor Injection
- Setter Injection
- Interface-based injection
Constructor injection uses parameters to inject dependencies. In setter injection, you use setter methods to inject the object's dependencies. Finally, in interface-based injection, you design an interface to inject dependencies. The following section shows how to implement each of these dependency injection forms and discusses the pros and cons of each.
Implementing Constructor Injection
I'll begin this discussion by implementing the first type of dependency injection mentioned in the preceding sectionconstructor injection. Consider a design with two layers; a BusinessFacade layer and the BusinessLogic layer. The BusinessFacade layer of the application depends on the BusinessLogic layer to operate properly. All the business logic classes implement an IBusinessLogic interface.
With constructor injection, you'd create an instance of the BusinessFacade class using its argument or parameterized constructor and pass the required BusinessLogic type to inject the dependency. The following code snippet illustrates the concept, showing the BusinessLogic and BusinessFacade classes.
class ProductBL : IBusinessLogic
class CustomerBL : IBusinessLogic
public class BusinessFacade
private IBusinessLogic businessLogic;
public BusinessFacade(IBusinessLogic businessLogic)
this.businessLogic = businessLogic;
You'd instantiate the BusinessLogic classes (ProductBL or CustomerBL) as shown below:
IBusinessLogic productBL = new ProductBL();
Then you can pass the appropriate type to the BusinessFacade class when you instantiate it:
BusinessFacade businessFacade = new BusinessFacade(productBL);
Note that you can pass an instance of either BusinssLogic class to the BusinessFacade class constructor. The constructor does not accept a concrete object; instead, it accepts any class that implements the IBusinessLogic interface.
Even though it is flexible and promotes loose coupling, the major drawback of constructor injection is that once the class is instantiated, you can no longer change the object's dependency. Further, because you can't inherit constructors, any derived classes call a base class constructor to apply the dependencies properly. Fortunately, you can overcome this drawback using the setter injection technique.