Home >Backend Development >C#.Net Tutorial >How to implement dependency injection using interface-based injection in C#?

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

王林
王林forward
2023-09-07 20:09:071318browse

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

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

Types of dependency injection

DI has four types −

  • Constructor injection

  • Setter Injection

  • Interface-based injection

  • Service locator injection

Interface injection

Interface injection is similar to Getter and Setter DI. Getter and Setter DI use default getters and setters, but interface injection uses a supporting interface (an explicit getter and setter that sets interface properties).

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());
   }
}

Consumption

BusinessLogicImplementationInterfaceDI objInterfaceDI =
new BusinessLogicImplementationInterfaceDI();
objInterfaceDI= new ClaimService();
objInterfaceDI.setServiceRunService(serviceObj);

The above is the detailed content of How to implement dependency injection using interface-based injection in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete