How to implement Dependency Injection using Property 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

Setter Injection

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

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";
   }
}
public class BusinessLogicImplementation{
   private IService _client;
   public IService Client{
      get { return _client; }
      set { _client = value; }
   }
   public void SetterInj(){
      Console.WriteLine("Getter and Setter Injection ==>
      Current Service : {0}", Client.ServiceMethod());
   }
}

Consuming

BusinessLogicImplementation ConInjBusinessLogic = new BusinessLogicImplementation();
ConInjBusinessLogic.Client = new ClaimService();
ConInjBusinessLogic.SetterInj();
raja
Published on 05-Dec-2020 06:40:45
Advertisements