What are the different ways to implement dependency injection and their advantages in C#?

The process of injecting (converting) coupled (dependent) objects into decoupled (independent) objects is called Dependency Injection.

Types of Dependency Injection

There are four types of DI:

1.Constructor Injection

2.Setter Injection

3.Interface-based injection

4.Service Locator Injection

Constructor Injection

Constructor is used to interface parameter that exposed through the parameterized contractor.

It injects the dependencies through a contractor method as object creation other classes.

Setter Injection

Getter and Setter Injection injects the dependency by using default public properties procedure such as Gettter(get(){}) and Setter(set(){}). T

Interface Injection

Interface Injection is similar to Getter and Setter DI, the Getter and Setter DI uses default getter and setter but Interface Injection uses support interface a kind of explicit getter and setter which sets the interface property.

Service Locator Injection

Service Locator Injection is also known as Dependency Absorption. It is used to replacement of new operator. It hides the class dependency by invoking methods directly (without creating object).

Advantages of DI

Reduces class coupling

Increases code reusability

Improves code maintainability

Improves application testing

Centralized configuration

Drawback of dependency Injection

The main drawback of dependency injection is that using many instances together can become a very difficult if there are too many instances and many dependencies that need to be resolved.