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#?

王林
Release: 2023-09-07 20:09:07
forward
1364 people have browsed it

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

Consumption

BusinessLogicImplementationInterfaceDI objInterfaceDI =
new BusinessLogicImplementationInterfaceDI();
objInterfaceDI= new ClaimService();
objInterfaceDI.setServiceRunService(serviceObj);
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template