.NET依賴註入之一個介面多個實現

来源:https://www.cnblogs.com/netry/archive/2023/02/26/net-dependency-injection-multiple-implementations.html
-Advertisement-
Play Games

前言 最近又在項目中碰到需要將原本單實現的介面改造成多個實現的場景,這裡記錄一下常見的幾種改法。 假設已經存在如下介面ICustomService和其實現CustomService,由於只有一種實現,註入和使用非常容易。 public interface ICustomService { void ...


前言

最近又在項目中碰到需要將原本單實現的介面改造成多個實現的場景,這裡記錄一下常見的幾種改法。

假設已經存在如下介面ICustomService和其實現CustomService,由於只有一種實現,註入和使用非常容易。

public interface ICustomService
{
    void MethodA();
    void MethodB();
}
public class CustomService: ICustomService
{
    public void MethodA()
    {
    }

    public void MethodB()
    {
    }
}

//註入
builder.Services.AddTransient<ICustomService, CustomService>();

//使用
private readonly ICustomService _customService;
public CustomController(ICustomService customService)
{
  _customService = customService;
}

現在我們需要增加一種實現。

使用多個介面實現

我們可以將原ICustomService內的方法移到到一個新的基介面,共用出來,需要多少個實現,就創建多少個空介面繼承該基介面。

//基介面
public interface ICustomBaseService
{
    void MethodA();
    void MethodB();
}

//多個空介面
public interface ICustomService : ICustomBaseService
{
}

public interface ICustomServiceV2 : ICustomBaseService
{
}

//第一種實現
public class CustomService: ICustomService
{
    public void MethodA()
    {
    }

    public void MethodB()
    {
    }
}

//第二種實現
public class CustomServiceV2: ICustomServiceV2
{
    public void MethodA()
    {
    }

    public void MethodB()
    {
    }
}

//註入
builder.Services.AddTransient<ICustomService, CustomService>();
builder.Services.AddTransient<ICustomServiceV2, CustomServiceV2>();


//使用
private readonly ICustomService _customService;
private readonly ICustomServiceV2 _customServiceV2;
public CustomController(ICustomService customService,ICustomServiceV2 customServiceV2)
{
  _customService = customService;
  _customServiceV2 = customServiceV2;
}

這種實現方式需要增加了一套空介面做隔離,看似可能比較“浪費”,但後期隨著項目的演進,ICustomServiceICustomServiceV2可能會慢慢分化,我們可以很方便的為它們擴充各種獨有方法。

使用單介面實現

如果我們確定不要要多個介面,也可以使用下麵的單介面實現

public interface ICustomService
{
    void MethodA();
    void MethodB();
}

//第一種實現
public class CustomService: ICustomService
{
    public void MethodA()
    {
    }

    public void MethodB()
    {
    }
}

//第二種實現
public class CustomServiceV2: ICustomService
{
    public void MethodA()
    {
    }

    public void MethodB()
    {
    }
}

//註入
builder.Services.AddTransient<ICustomService, CustomService>();
builder.Services.AddTransient<ICustomService, CustomServiceV2>();


//使用
private readonly ICustomService _customService;
private readonly ICustomService _customServiceV2;
public CustomController(IEnumerable<ICustomService> customServices)
{
 _customService = customServices.ElementAt(0);
 _customServiceV2 = customServices.ElementAt(1);
}

從上面代碼可以看到,我們是為從介面ICustomService註冊兩個實現,並從IEnumerable<ICustomService>解析出了這兩個實現。這裡可能會有兩個疑問

  1. 為什麼第一個實現CustomService沒有被第二個實現CustomServiceV2替換掉?
  2. 為什麼可以從IEnumerable<ICustomService>解析到我們需要的服務?

答案在Microsoft.Extensions.DependencyInjection.ServiceDescriptorMicrosoft.Extensions.DependencyInjection.ServiceCollection 這兩個類里,進程里,依賴註入的服務,會被添加到ServiceCollection里,ServiceCollection是一組ServiceDescriptor的集合,ServiceDescriptor通過服務類型、實現以及生命周期三個組合在一起構成的標識來確定服務。而ICustomService+CustomService+TransientICustomService+CustomServiceV2+Transient是兩個不同的ServiceDescriptor,因此不會被替換。同時服務類型的ServiceDescriptor會被聚合在一起,於是我們可以很方便的從IEnumerable對象中解析出所有的同類型的服務。

總結

本質上,兩種方法都是多態性(Polymorphism)的應用,沒有優劣之分,根據場景選擇合適的寫法。

鏈接

https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
https://github.com/dotnet/runtime

作者: 幾秋

出處: https://www.cnblogs.com/netry/p/net-dependency-injection-multiple-implementations.html

本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 歡迎關註個人公眾號:愛喝可可牛奶 LeetCode 39. 組合總和 40.組合總和II 131.分割迴文串 LeetCode 39. 組合總和 分析 回溯可看成對二叉樹節點進行組合枚舉,分為橫向和縱向 每次往sum添加新元素時,必須明確從can哪個位置開始,定義變數pos 返回條件 sum == ...
  • 一、m_sequencer 1、什麼是m_sequencer m_sequencer是定義在uvm_sequencer_item中的,uvm_sequencer_base類型的句柄,也就是說 m_sequencer是uvm_sequencer_item的成員變數 m_sequencer是指向uvm_ ...
  • 1、變數 推薦 駝峰體:AgeOfOldboy = 73 下劃線:age_of_oldboy = 73 # 變數的小高級: age1 = 18 age2 = age1 age3 = age2 age2 = 12 print(age1,age2,age3) 18 12 18 Process finis ...
  • 這篇文章主要關註分散式系統中的數據複製,它提高了系統的可用性和可靠性,保證業務正常運行。常見的數據複製方法包括同步複製技術、非同步複製技術和半同步複製技術。 ...
  • 編寫API可能對於很多後端開發人員來說,並不是什麼難事兒,但如果您主要從事前端功能,那麼可能還是有一些門檻。 那麼有沒有工具可以幫助我們降低編寫API的學習門檻和複雜度呢? 今天就來給大家推薦一個不錯的開源工具:APITable APITable是一個面向API的可視化資料庫,它適用於所有人,甚至沒 ...
  • 前言 在並行開發時我們經常會用到Pstream::gather()函數或是全局函數reduce()或者其他,需要輸入參數Binary &Op,本篇主要討論Binary &Op是什麼 template<class T, class BinaryOp> void reduce ( T& Value, c ...
  • Spring Bean 作用域 主要瞭解 singleton 和 prototype 就好了,他們分別使用 單例模式 和 原型模式 | 來源 | 說明 | | | | | singleton | 預設作用域,一個BeanFactory有且僅有一個實例(並不是在JVM進程里是唯一的) | | prot ...
  • 問題描述 最近在做一個web demo時遇到了一個問題,運行提示:未能載入文件或程式集"...\App_global.asax.*.dll"或它的一個依賴項,在網上搜到的呢都是因為沒有引用另一個項目導致的,而我這個是只有一個項目,所以也就不存在未引用其他項目的原因,可是就是找不到問題。 附圖: 出現 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...