在 C# 中如何使用基於介面的注入實現依賴注入?


將繫結(依賴)物件注入(轉換)到取消繫結(獨立)物件的程序稱為依賴注入。

依賴注入型別

DI 有四種類型- -

  • 建構函式注入

  • Setter 注入

  • 基於介面的注入

  • 服務定位器注入

介面注入

介面注入與 Getter 和 Setter DI 相似,Getter 和 Setter DI 使用預設 getter 和 setter,但介面注入使用支援一種顯示 getter 和 setter 的介面,該介面設定介面屬性。

示例

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

使用

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

更新於: 05-12-2020

3K+ 瀏覽

開啟你的 職業

完成課程,獲得認證

開始吧
廣告