Browse DevX
Sign up for e-mail newsletters from DevX


Three Ways to Implement Dependency Injection in .NET Applications : Page 2

Replace dependencies with Dependency Injection pattern code to make your classes easier to test and reuse.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Types of Dependency Injection
There are three common forms of dependency injection:

  1. Constructor Injection
  2. Setter Injection
  3. 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 section—constructor 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.

interface IBusinessLogic { //Some code } class ProductBL : IBusinessLogic { //Some code } class CustomerBL : IBusinessLogic { //Some code } 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.

Thanks for your registration, follow us on our social networks to keep up-to-date