Dependency Injection in C Sharp

|
| By Webner

To understand the term Dependency Injection, we must know what is Dependency and IoC?
In terms of Object-Oriented Programming, Suppose Class A uses Class B for one of its jobs. Here Class B is a dependency of Class A and Class A is dependent on class B.
IoC stands for Inversion of Control. It is a software design principle of programming style in which the flow of programming is changed or inverted from the normal way. It is all about inverting the control.
Let’s understand this through a real-world example:
Suppose you drive a car to your workplace means control of the car is in your hands. IoC principle suggests inverting the control. Now instead of driving yourself, you hire a cab. Here, another person will drive the car. You can let the driver do driving and you can focus on your main work. Thus, called Inversion of Control – from you to the cab driver.
IoC helps in designing loosely coupled classes means reducing dependencies between classes.
Dependency Injection is a software design pattern used to implement IoC. Using DI, we move the creation and binding of dependent objects outside of the class that depends on them.
It involves three types of classes:

  1. Client Class: The Client class (dependent class) is a class that depends on the service class.
  2. Service Class: The Service class (dependency) is a class that provides service to the dependent class.
  3. Injector Class: The Injector class injects the object of the service class into the client class.

In Simpler words, the injector class creates an object of service class and injects it into the client class.
In this way, DI separates the responsibility of creating an object of service class out of the client class.

The Injector class injects dependencies through following ways:

  1. Constructor Injection: In this process, one parameterized constructor is used in which dependency of the class is passed as a parameter at the time of object creation.

    Example:
    Dependency

  2. Property Injection: Dependency is supplied through a public property of dependent class.

    Example:
    code2

  3. Method Injection: Dependencies to a class is provided through methods and that method could be a interface method or class method.

    Example:
    code3

Advantages of Dependency Injection:

  1. Allows making loosely coupled and maintainable code.
  2. Implements IoC by reducing hard code dependencies between classes and passing those dependencies at runtime.
  3. Makes code more readable leads to easier maintenance of code.
  4. Results in a more extendable class structure.

Leave a Reply

Your email address will not be published. Required fields are marked *