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

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(){}).

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());
   }
}
BusinessLogicImplementation ConInjBusinessLogic = new BusinessLogicImplementation();
ConInjBusinessLogic.Client = new ClaimService();
ConInjBusinessLogic.SetterInj();

0 Comment's

Comment Form

Submit Comment