C# Autofac學習筆記

来源:https://www.cnblogs.com/atomy/archive/2020/05/08/12834804.html
-Advertisement-
Play Games

一、為什麼使用Autofac? Autofac是.NET領域最為流行的IoC框架之一,傳說是速度最快的一個。 1.1、性能 有人專門做了測試: 1.2、優點 1)與C#語言聯繫很緊密。C#里的很多編程方式都可以為Autofac使用,例如可以使用Lambda表達式註冊組件。 2)較低的學習曲線。學習它 ...


    一、為什麼使用Autofac?

    Autofac是.NET領域最為流行的IoC框架之一,傳說是速度最快的一個。

    1.1、性能

    有人專門做了測試:

    1.2、優點

    1)與C#語言聯繫很緊密。C#里的很多編程方式都可以為Autofac使用,例如可以使用Lambda表達式註冊組件。

    2)較低的學習曲線。學習它非常的簡單,只要你理解了IoC和DI的概念以及在何時需要使用它們。

    3)支持JSON/XML配置。

    4)自動裝配。

    5)與Asp.Net MVC集成。

    6)微軟的Orchad開源程式使用的就是Autofac,可以看出它的方便和強大。

    1.3、資源

    官方網站:http://autofac.org/

    GitHub網址:https://github.com/autofac/Autofac

    學習資料:Autofac中文文檔

    二、數據準備

    2.1、新建項目

    IService下的介面類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 動物吠聲介面類
    /// </summary>
    public interface IAnimalBark
    {
        /// <summary>
        /// 吠叫
        /// </summary>
        void Bark();
    }
}
IAnimalBark
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 動物睡眠介面類
    /// </summary>
    public interface IAnimalSleep
    {
        /// <summary>
        /// 睡眠
        /// </summary>
        void Sleep();
    }
}
IAnimalSleep
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 學校介面類
    /// </summary>
    public interface ISchool
    {
        /// <summary>
        /// 放學
        /// </summary>
        void LeaveSchool();
    }
}
ISchool
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkTo.Test.Autofac.IService
{
    /// <summary>
    /// 學生介面類
    /// </summary>
    public interface IStudent
    {
        /// <summary>
        /// 增加學生
        /// </summary>
        /// <param name="studentID">學生ID</param>
        /// <param name="studentName">學生姓名</param>
        void Add(string studentID, string studentName);
    }
}
IStudent

    Service下的介面實現類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 貓類
    /// </summary>
    public class Cat : IAnimalSleep
    {
        /// <summary>
        /// 睡眠
        /// </summary>
        public void Sleep()
        {
            Console.WriteLine("小貓咪睡著了zZ");
        }
    }
}
Cat
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 狗類
    /// </summary>
    public class Dog : IAnimalBark, IAnimalSleep
    {
        /// <summary>
        /// 吠叫
        /// </summary>
        public void Bark()
        {
            Console.WriteLine("汪汪汪");
        }

        /// <summary>
        /// 睡眠
        /// </summary>
        public void Sleep()
        {
            Console.WriteLine("小狗狗睡著了zZ");
        }
    }
}
Dog
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 學校類
    /// </summary>
    public class School : ISchool
    {
        /// <summary>
        /// IAnimalBark屬性
        /// </summary>
        public IAnimalBark AnimalBark { get; set; }

        /// <summary>
        /// 放學
        /// </summary>
        public void LeaveSchool()
        {
            AnimalBark.Bark();
            Console.WriteLine("你家的熊孩子放學了⊙o⊙");
        }
    }
}
School
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 學生類
    /// </summary>
    public class Student : IStudent
    {
        /// <summary>
        /// 無參構造函數
        /// </summary>
        public Student()
        { }

        /// <summary>
        /// 有參構造函數
        /// </summary>
        /// <param name="studentID">學生ID</param>
        /// <param name="studentName">學生姓名</param>
        public Student(string studentID, string studentName)
        {
            Add(studentID, studentName);
        }

        /// <summary>
        /// 增加學生
        /// </summary>
        /// <param name="studentID">學生ID</param>
        /// <param name="studentName">學生姓名</param>
        public void Add(string studentID, string studentName)
        {
            Console.WriteLine($"新增的學生是:{studentName}");
        }
    }
}
Student
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LinkTo.Test.Autofac.IService;

namespace LinkTo.Test.Autofac.Service
{
    /// <summary>
    /// 動物搖尾巴
    /// </summary>
    public class AnimalWagging
    {
        /// <summary>
        /// IAnimalBark屬性
        /// </summary>
        IAnimalBark animalBark;

        /// <summary>
        /// 有參構造函數
        /// </summary>
        /// <param name="bark">IAnimalBark變數</param>
        public AnimalWagging(IAnimalBark bark)
        {
            animalBark = bark;
        }

        /// <summary>
        /// 搖尾巴
        /// </summary>
        public virtual void Wagging()
        {
            animalBark.Bark();
            Console.WriteLine("搖尾巴");
        }

        /// <summary>
        /// 計數
        /// </summary>
        /// <returns></returns>
        public static int Count()
        {
            return 6;
        }

        /// <summary>
        /// 任務
        /// </summary>
        /// <param name="name">動物名稱</param>
        /// <returns></returns>
        public virtual async Task<string> WaggingAsync(string name)
        {
            var result = await Task.Run(() => Count());
            return $"{name}搖了{result}下尾巴";
        }
    }
}
AnimalWagging

    2.2、Autofac安裝

    Client項目右鍵->管理 NuGet 程式包->Autofac。

    三、IoC-註冊

    3.1、類型註冊

    a)類型註冊:使用RegisterType進行註冊。

            //註冊Autofac組件
            ContainerBuilder builder = new ContainerBuilder();
            //註冊實現類Student,當我們請求IStudent介面的時候,返回的是類Student的對象。
            builder.RegisterType<Student>().As<IStudent>();
            //上面這句也可改成下麵這句,這樣請求Student實現了的任何介面的時候,都會返回Student對象。
            //builder.RegisterType<Student>().AsImplementedInterfaces();
            IContainer container = builder.Build();
            //請求IStudent介面
            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");
View Code

    b)類型註冊(別名):假如一個介面有多個實現類,可以在註冊時起別名。

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Dog>().Named<IAnimalSleep>("Dog");
            builder.RegisterType<Cat>().Named<IAnimalSleep>("Cat");
            IContainer container = builder.Build();

            var dog = container.ResolveNamed<IAnimalSleep>("Dog");
            dog.Sleep();
            var cat = container.ResolveNamed<IAnimalSleep>("Cat");
            cat.Sleep();
View Code

    c)類型註冊(枚舉):假如一個介面有多個實現類,也可以使用枚舉的方式註冊。

        public enum AnimalType
        {
            Dog,
            Cat
        }
View Code
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Dog>().Keyed<IAnimalSleep>(AnimalType.Dog);
            builder.RegisterType<Cat>().Keyed<IAnimalSleep>(AnimalType.Cat);
            IContainer container = builder.Build();

            var dog = container.ResolveKeyed<IAnimalSleep>(AnimalType.Dog);
            dog.Sleep();
            var cat = container.ResolveKeyed<IAnimalSleep>(AnimalType.Cat);
            cat.Sleep();
View Code

    3.2、實例註冊

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterInstance<IStudent>(new Student());
            IContainer container = builder.Build();

            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");
View Code

    3.3、Lambda註冊

    a)Lambda註冊

            ContainerBuilder builder = new ContainerBuilder();
            builder.Register(c => new Student()).As<IStudent>();
            IContainer container = builder.Build();

            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");
View Code

    b)Lambda註冊(NamedParameter)

            ContainerBuilder builder = new ContainerBuilder();
            builder.Register<IAnimalSleep>((c, p) =>
                {
                    var type = p.Named<string>("type");
                    if (type == "Dog")
                    {
                        return new Dog();
                    }
                    else
                    {
                        return new Cat();
                    }
                }).As<IAnimalSleep>();
            IContainer container = builder.Build();

            var dog = container.Resolve<IAnimalSleep>(new NamedParameter("type", "Dog"));
            dog.Sleep();
View Code

    3.4、程式集註冊

    如果有很多介面及實現類,假如覺得這種一一註冊很麻煩的話,可以一次性全部註冊,當然也可以加篩選條件。

            ContainerBuilder builder = new ContainerBuilder();
            Assembly assembly = Assembly.Load("LinkTo.Test.Autofac.Service");   //實現類所在的程式集名稱
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();  //常用
            //builder.RegisterAssemblyTypes(assembly).Where(t=>t.Name.StartsWith("S")).AsImplementedInterfaces();  //帶篩選
            //builder.RegisterAssemblyTypes(assembly).Except<School>().AsImplementedInterfaces();  //帶篩選
            IContainer container = builder.Build();

            //單實現類的用法
            IStudent student = container.Resolve<IStudent>();
            student.Add("1001", "Hello");

            //多實現類的用法
            IEnumerable<IAnimalSleep> animals = container.Resolve<IEnumerable<IAnimalSleep>>();
            foreach (var item in animals)
            {
                item.Sleep();
            }
View Code

    3.5、泛型註冊

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterGeneric(typeof(List<>)).As(typeof(IList<>));
            IContainer container = builder.Build();

            IList<string> list = container.Resolve<IList<string>>();
View Code

    3.6、預設註冊

            ContainerBuilder builder = new ContainerBuilder();
            //對於同一個介面,後面註冊的實現會覆蓋之前的實現。
            //如果不想覆蓋的話,可以用PreserveExistingDefaults,這樣會保留原來註冊的實現。
            builder.RegisterType<Dog>().As<IAnimalSleep>();
            builder.RegisterType<Cat>().As<IAnimalSleep>().PreserveExistingDefaults();  //指定為非預設值
            IContainer container = builder.Build();

            var dog = container.Resolve<IAnimalSleep>();
            dog.Sleep();
View Code

    四、IoC-註入

    4.1、構造函數註入

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<AnimalWagging>();
            builder.RegisterType<Dog>().As<IAnimalBark>();
            IContainer container = builder.Build();

            AnimalWagging animal = container.Resolve<AnimalWagging>();
            animal.Wagging();
View Code

    4.2、屬性註入

            ContainerBuilder builder = new ContainerBuilder();
            Assembly assembly = Assembly.Load("LinkTo.Test.Autofac.Service");                           //實現類所在的程式集名稱
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces().PropertiesAutowired();    //常用
            IContainer container = builder.Build();

            ISchool school = container.Resolve<ISchool>();
            school.LeaveSchool();
View Code

    五、IoC-事件

    Autofac在組件生命周期的不同階段,共對應了5個事件,執行順序如下所示:

    1.OnRegistered->2.OnPreparing->3.OnActivating->4.OnActivated->5.OnRelease

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Student>().As<IStudent>()
                .OnRegistered(e => Console.WriteLine("OnRegistered:在註冊的時候調用"))
                .OnPreparing(e => Console.WriteLine("OnPreparing:在準備創建的時候調用"))
                .OnActivating(e => Console.WriteLine("OnActivating:在創建之前調用"))
                //.OnActivating(e => e.ReplaceInstance(new Student("1000", "Test")))
                .OnActivated(e => Console.WriteLine("OnActivated:在創建之後調用"))
                .OnRelease(e => Console.WriteLine("OnRelease:在釋放占用的資源之前調用"));
            using (IContainer container = builder.Build())
            {
                IStudent student = container.Resolve<IStudent>();
                student.Add("1001", "Hello");
            }
View Code

    六、IoC-生命周期

    6.1、Per Dependency

    Per Dependency:為預設的生命周期,也被稱為"transient"或"factory",其實就是每次請求都創建一個新的對象。

            ContainerBuilder builder = new ContainerBuilder();
            Assembly assembly = Assembly.Load("LinkTo.Test.Autofac.Service");                                                   //實現類所在的程式集名稱
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency();    //常用
            IContainer container = builder.Build();

            ISchool school1 = container.Resolve<ISchool>();
            ISchool school2 = container.Resolve<ISchool>();
            Console.WriteLine(school1.Equals(school2));
View Code

    6.2、Single Instance

    Single Instance:就是每次都用同一個對象。

            ContainerBuilder builder = new ContainerBuilder();
            Assembly assembly = Assembly.Load("LinkTo.Test.Autofac.Service");                                           //實現類所在的程式集名稱
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces().PropertiesAutowired().SingleInstance();   //常用
            IContainer container = builder.Build();

            ISchool school1 = container.Resolve<ISchool>();
            ISchool school2 = container.Resolve<ISchool>();
            Console.WriteLine(ReferenceEquals(school1, school2));
View Code

    6.3、Per Lifetime Scope

    Per Lifetime Scope:同一個Lifetime生成的對象是同一個實例。

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<School>().As<ISchool>().InstancePerLifetimeScope();
            IContainer container = builder.Build();
            ISchool school1 = container.Resolve<ISchool>();
            ISchool school2 = container.Resolve<ISchool>();
            Console.WriteLine(school1.Equals(school2));
            using (ILifetimeScope lifetime = container.BeginLifetimeScope())
            {
                ISchool school3 = lifetime.Resolve<ISchool>();
                ISchool school4 = lifetime.Resolve<ISchool>();
                Console.WriteLine(school3.Equals(school4));
                Console.WriteLine(school2.Equals(school3));
            }
View Code

    七、IoC-通過配置文件使用Autofac

    7.1、組件安裝

    Client項目右鍵->管理 NuGet 程式包->Autofac.Configuration及Microsoft.Extensions.Configuration.Xml。

    7.2、配置文件

    新建一個AutofacConfigIoC.xml文件,在其屬性的複製到輸出目錄項下選擇始終複製。

<?xml version="1.0" encoding="utf-8" ?>
<autofac defaultAssembly="LinkTo.Test.Autofac.IService">
  <!--無註入-->
  <components name="1001">
    <type>LinkTo.Test.Autofac.Service.Student, LinkTo.Test.Autofac.Service</type>
    <services name="0" type="LinkTo.Test.Autofac.IService.IStudent" />
    <injectProperties>true</injectProperties>
  </components>
  <components name="1002">
    <type>LinkTo.Test.Autofac.Service.Dog, LinkTo.Test.Autofac.Service</type>
    <services name="0" type="LinkTo.Test.Autofac.IService.IAnimalBark" />
    <injectProperties>true</injectProperties>
  </components>
  <!--構造函數註入-->
  <components name="2001">
    <type>LinkTo.Test.Autofac.Service.AnimalWagging, LinkTo.Test.Autofac.Service</type>
    <services name="0" type="LinkTo.Test.Autofac.Service.AnimalWagging, LinkTo.Test.Autofac.Service" />
    <injectProperties>true</injectProperties>
  </components>
  <!--屬性註入-->
  <components name="3001">
    	   

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

-Advertisement-
Play Games
更多相關文章
  • Spring 是一個主流的 Java Web 開發框架,該框架是一個輕量級的應用框架,具有很高的凝聚力和吸引力。Spring使每個人都可以更快,更輕鬆,更安全地進行Java編程。Spring對速度,簡單性和生產率的關註使其成為世界上最受歡迎的 Java框架。 Spring 是分層的 Java SE/... ...
  • 題目:古典問題(兔子生崽):有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?(輸出前40個月即可) 程式分析:兔子的規律為數列1,1,2,3,5,8,13,21....,即下個月是上兩個月之和(從第三個月開始)。 程 ...
  • 題目:列印樓梯,同時在樓梯上方列印兩個笑臉。 程式分析:用 ASCII 1 來輸出笑臉;用i控制行,j來控制列,j根據i的變化來控制輸出黑方格的個數。 如果出現亂碼情況請參考 C 實戰練習題目7 的解決方法。 1 #include<stdio.h> 2 3 int main() 4 { 5 int ...
  • https://www.bilibili.com/video/BV15x411x7WN?p=2這個視頻有點模糊,勉強看個思路。 第一集:安裝dev套件,安裝的時候需要把vs關掉。安裝成功後,如果工具箱沒有看見dev控制項,可以在工具箱->選擇工具箱選項里添加控制項,主要添加命名空間是devexpress ...
  • 一:背景 1. 講故事 前幾天公眾號里有位兄弟看了幾篇文章之後,也準備用windbg試試看,結果這一配就花了好幾天,(づ╥﹏╥)づ,我想也有很多躍躍欲試的朋友在配置的時候肯定會遇到這樣和那樣的問題,所以我覺得有必要整理一下,讓大家少走彎路。 二:一些基礎概念 1. 在哪下載 現在安裝windbg越來 ...
  • 需求:錄入表達式計算出值 .net 後臺:DataTable有個函數:Compute 具體用法可自行百度 案例:錄入表達式 1 1/2 獲取百分比值 string value=(Convert.ToDouble(dt.Compute(dt.Rows[i][0].ToString(),"false") ...
  • CAP源碼追蹤(一)消息是如何執行的,執行後又是如何執行回調的 場景 .NET Core 3.1 nuget包:DotNetCore.CAP.RabbitMQ 3.0.2 前言 以對話為引,梳理我們的問題: 小明 聰明絕頂的程式猿,小紅 絕美程式媛 小紅:小明,在CAP中,我們通過 CapSubsc ...
  • 適用:.net framework 2.0+ winform項目 效果: 倉庫:https://github.com/ahdung/SystemMenuUtil -文畢- ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...