How to implement dependency injection using Interface-based injection in C#?

CsharpServer Side ProgrammingProgramming

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 −

  • Constructor Injection

  • Setter Injection

  • Interface-based injection

  • Service Locator Injection

Interface Injection

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

Example

public interface IService{
   string ServiceMethod();
}
public class ClaimService:IService{
   public string ServiceMethod(){
      return "ClaimService is running";
   }
}
public class AdjudicationService:IService{
   public string ServiceMethod(){
      return "AdjudicationService is running";
   }
}
interface ISetService{
   void setServiceRunService(IService client);
}
public class BusinessLogicImplementationInterfaceDI : ISetService{
   IService _client1;
   public void setServiceRunService(IService client){
      _client1 = client;
      Console.WriteLine("Interface Injection ==>
      Current Service : {0}", _client1.ServiceMethod());
   }
}

Consuming

BusinessLogicImplementationInterfaceDI objInterfaceDI =
new BusinessLogicImplementationInterfaceDI();
objInterfaceDI= new ClaimService();
objInterfaceDI.setServiceRunService(serviceObj);
raja
Published on 05-Dec-2020 11:12:30
Advertisements