.NET6.0實現IOC容器

来源:https://www.cnblogs.com/ycit/archive/2023/09/05/17680238.html
-Advertisement-
Play Games

# .NET6.0實現IOC容器 `IOC`的作用這裡省略…只對如何使用進行說明。 ## 1. 創建一個.NET6應用程式 這裡使用` .NET6.0 WebAPI` 應用 ## 2. 聲明介面 ```c public interface IAuthService { bool CheckToken ...


.NET6.0實現IOC容器

IOC的作用這裡省略…只對如何使用進行說明。

1. 創建一個.NET6應用程式

這裡使用 .NET6.0 WebAPI 應用

2. 聲明介面

  public interface IAuthService
  {
        bool CheckToken();
  }

3. 實現介面

class AuthServiceImpl : IAuthService
{
        public bool CheckToken()
        {
            Console.WriteLine("check token");
            return true;
        }
}

4. 配置IOC容器

下麵是在 program 類中的代碼

var services = new ServiceCollection();
services.AddSingleton<IAuthService, AuthServiceImpl>();

5. 獲取服務

通過在 Controller的構造函數中註入IAuthService

		private readonly IAuthService _service;  
		public WeatherForecastController(IAuthService service)
        {
            _service = service;
        }

        [HttpGet(Name = "test")]
        public bool Get()
        {
           return _service.CheckToken();
        }

啟動後,通過swagger發起請求,驗證介面。

基本IOC容器流程已實現。但是這樣存在一個弊端,每個介面和實現都要在program中手動註冊一遍,還要在Controller構造函數中進行依賴註入,有沒有能自動實現註冊代替program中的手動註冊?

接下來,對上述流程進行改良。

6. 改良思路

定義一個AutowiredAttribute標記,通過Atrribute標記的方式,在實現類上標記其要實現的介面服務,然後實現一個服務載入類ServiceLoader,在這個類中反射獲取所有具備AutoIocAttribute的實現類,然後註冊到ServiceCollection中。

6.1 定義特性標記AutowiredAttribute

    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public class AutowiredAttribute : Attribute
    {
        /// <summary>
        /// 介面
        /// </summary>
        public Type Iface { get; set; }
        /// <summary>
        /// 實現類名
        /// </summary>
        public string ImplClassName { get; set; }

        public AutowiredAttribute(Type iface, [CallerMemberName] string implClassName = "")
        {
            Iface = iface;
            ImplClassName = implClassName;
        }
    }

6.2 實現服務載入類

利用IServiceCollection作為服務容器

    public class ServiceLoader
    {
        private static object _lock = new object();
        private static AppRuntime _inst;
        private readonly IServiceCollection _iocService = new ServiceCollection();
        private readonly ICollection<Assembly> _iocAssembly = new HashSet<Assembly>();
        private IServiceProvider _iocServiceProvider = null;


        public static ServiceLoader Instance
        {
            get
            {
                if (_inst == null)
                {
                    lock (_lock)
                    {
                        _inst = new ServiceLoader();
                        _inst.Startup(typeof(ServiceLoader).Assembly);
                    }
                }
                return _inst;
            }
        }

        public T GetService<T>()
        {
            EnsureAutoIoc<T>();
            return _iocServiceProvider.GetService<T>();
        }

        private void EnsureAutoIoc<T>()
        {
            Startup(typeof(T).Assembly);
        }

        public void Startup(Assembly ass)
        {
            if (_iocAssembly.Any(x => x == ass))
            {
                return;
            }
            _iocAssembly.Add(ass);

            var types = ass.GetTypes().Where(x => x.GetCustomAttribute<AutowiredAttribute>() != null);
            foreach (var item in types)
            {
                var autoIocAtt = item.GetCustomAttribute<AutowiredAttribute>();
                AddTransient(autoIocAtt.Iface, item);
            }
            //_iocServiceProvider = _iocService.BuildServiceProvider();
            Interlocked.Exchange(ref _iocServiceProvider, _iocService.BuildServiceProvider());
        }

        private void AddTransient(Type iface, Type impl)
        {
            _iocService.AddTransient(iface, impl);
        }
    }

6.3 在實現類加上標記

    [Autowired(typeof(IAuthService))]
    class AuthServiceImpl : IAuthService
    {
    
        public bool CheckToken()
        {
            Console.WriteLine("check token");
            return true;
        }
    }

6.4 在 Controller 中調用

   var svc = ServiceLoader.Instance.GetService<IAuthService>();
   svc.CheckToken();

至此一個基本的完整IOC容器已實現。

本文來自博客園,作者:宣君{https://www.nhit.icu/},轉載請註明原文鏈接:https://www.cnblogs.com/ycit/p/17680238.html


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

-Advertisement-
Play Games
更多相關文章
  • 享元模式在主流的標準里是放到結構大類下的,但是我感覺這個模式的最終作用也是為了獲取一個類,所以我將其劃分到創建大類下。 # What is Flyweight Pattern Flyweight 是指輕量級的。 享元模式旨在支持大量細粒度的對象共用,以減少記憶體消耗。該模式通過共用相似對象的部分狀態, ...
  •  **多個word 文檔 轉化成 PDF 文件, 最後合併成一個PDF文件** ``` import os from win32com import client from PyPDF2 import PdfMerger # 使用PdfMerger def wordToPdf(folder): # ...
  • 2021年上半年,擼了個rust cli開發的框架,基本上把交互模式,子命令提示這些cli該有的常用功能做進去了。項目地址:[https://github.com/jiashiwen/interactcli-rs。](https://github.com/jiashiwen/interactcli- ...
  • 節表(Section Table)是Windows PE/COFF格式的可執行文件中一個非常重要的數據結構,它記錄了各個代碼段、數據段、資源段、重定向表等在文件中的位置和大小信息,是操作系統載入文件時根據節表來進行各個段的映射和初始化的重要依據。節表中的每個記錄則被稱為`IMAGE_SECTION_... ...
  • # 背景: ### 介紹 天網風控**靈璣**系統是基於記憶體計算實現的高吞吐低延遲線上計算服務,提供滑動或滾動視窗內的count、distinctCout、max、min、avg、sum、std及區間分佈類的線上統計計算服務。客戶端和服務端底層通過netty直接進行tcp通信,且服務端也是基於net ...
  • 巨集的一些作用,包括但不限於這些 1. 定義一個變數、字元串、類型 2. 定義一個函數、條件表達式 3. 條件編譯、調試信息,異常類 4. 定義結構體、命名空間 5. 定義模版、枚舉、函數對象 `#define`巨集定義在C++中用於定義常量、函數、條件編譯、字元串、條件表達式、變數、註釋、調試信息、類 ...
  • [toc] | 說明 | 內容 | | | | | 漏洞編號 | CVE-2017-10271 | | 漏洞名稱 | Weblogic 其中使用了XMLDecoder來解析用戶傳入的XML數據在解析的過程中出現反序列化漏洞,導致可執行任意命令 | | 修複方案 | 打補丁上設備升級組件 | ### ...
  • # 前言 在園子吸收營養10多年,一直沒有貢獻,目前園子危機時刻,除了捐款+會員,也鼓起勇氣,發篇文助力一下。 2018年下半年,公司決定開發一款SaaS版行業供應鏈管理系統,經過選型,確定採用ABP(ASP.NET Boilerplate)框架。為了加快開發效率,購買了商業版的 ASP.NET Z ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...