.NET 幫助

Autofac .NET 6(開發人員如何使用)

發佈 2024年7月1日
分享:

在 .NET 開發領域中,有效管理依賴對於構建可擴展、可維護和可測試的應用程序至關重要。依賴注入 (數字輸入) 容器透過實現控制反轉在達成這些目標中扮演了關鍵角色 (控制反轉) 原則。在眾多通用託管機制庫中,Autofac 脫穎而出,成為一個功能豐富且可擴展的 .NET 框架。

在本文中,我們將開始探索 Autofac .NET 6,揭示其功能和優勢,並展示其使用的實際示例。在本文的後半部分,我們將學習 IronPDF,這是 Iron Software 提供的一個 PDF 生成庫。我們還會展示一個 Autofac.NET 和 IronPDF 一起使用的實際案例。

理解 Autofac .NET

Autofac 是一個開源的 .NET IoC 容器,它為依賴注入和元件註冊在像 Web API 這樣的應用程式中提供了全面的支援。由 Nicholas Blumhardt 開發並由專門的社群維護,Autofac 提供了一個健全且靈活的解決方案,用於管理物件生命週期、解決依賴關係和組合應用程式元件。

Autofac 的特點

  1. 容器構建與元件註冊: 您可以使用 Autofac 在啟動類別中註冊元件來構建容器。您可以使用 lambda 表達式、類型或預先構建的實例來註冊元件。
    public class Startup
    {
        public void ConfigureContainer()
        {
            var builder = new ContainerBuilder(); // host sub property builder
            builder.RegisterInstance(new TaskRepository()).As<ITaskRepository>();
            builder.RegisterType<TaskController>();
            builder.Register(c => new LogManager(DateTime.Now)).As<ILogger>();
            // Scan an assembly for components
            builder.RegisterAssemblyTypes(myAssembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();
            var container = builder.Build();
        }
    }
    public class Startup
    {
        public void ConfigureContainer()
        {
            var builder = new ContainerBuilder(); // host sub property builder
            builder.RegisterInstance(new TaskRepository()).As<ITaskRepository>();
            builder.RegisterType<TaskController>();
            builder.Register(c => new LogManager(DateTime.Now)).As<ILogger>();
            // Scan an assembly for components
            builder.RegisterAssemblyTypes(myAssembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();
            var container = builder.Build();
        }
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 表達依賴性:Autofac 可以注入建構函數參數、處理屬性注入和方法注入。
    public class TaskController
    {
        private ITaskRepository _repository;
        private ILogger _logger;

        public TaskController(ITaskRepository repository, ILogger logger)
        {
            this._repository = repository;
            this._logger = logger;
        }
    }
    public class TaskController
    {
        private ITaskRepository _repository;
        private ILogger _logger;

        public TaskController(ITaskRepository repository, ILogger logger)
        {
            this._repository = repository;
            this._logger = logger;
        }
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 靈活的模組系統:Autofac 模組在 XML 配置和基於代碼的註冊之間取得了平衡。您可以在代碼中指定複雜的註冊,也可以使用 XML 更改部署時的行為。
    public class CarTransportModule : Module
    {
        public bool ObeySpeedLimit { get; set; }

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<Car>().As<IVehicle>();
            if (ObeySpeedLimit)
                builder.RegisterType<SaneDriver>().As<IDriver>();
            else
                builder.RegisterType<CrazyDriver>().As<IDriver>();
        }
    }
    public class CarTransportModule : Module
    {
        public bool ObeySpeedLimit { get; set; }

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<Car>().As<IVehicle>();
            if (ObeySpeedLimit)
                builder.RegisterType<SaneDriver>().As<IDriver>();
            else
                builder.RegisterType<CrazyDriver>().As<IDriver>();
        }
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 簡單擴展點: Autofac 提供激活事件以自定義元件的激活或釋放。
    var builder = new ContainerBuilder();
    builder.RegisterType<Listener>().As<IListener>().OnActivated(e => e.Instance.StartListening());
    builder.RegisterType<Processor>().OnActivating(e => e.Instance.Initialize());
    var container = builder.Build();
    var builder = new ContainerBuilder();
    builder.RegisterType<Listener>().As<IListener>().OnActivated(e => e.Instance.StartListening());
    builder.RegisterType<Processor>().OnActivating(e => e.Instance.Initialize());
    var container = builder.Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Autofac.NET的主要功能

  1. 靈活的組件註冊: Autofac允許開發人員使用各種註冊技術來註冊組件,包括手動註冊、程序集掃描和基於屬性的註冊。這種靈活性使得組件實例化和配置的控制更加精細。

  2. 生命周期管理: Autofac支持各種對象生命周期範圍,包括單例、每個依賴實例、每個生命周期範圍實例和每個請求實例。對對象生命周期的這種精細控制確保了資源的有效利用,並防止了長期運行應用程序中的內存泄漏。

  3. 自動解決依賴關係: Autofac根據註冊的組件註冊和它們的依賴關係自動解決依賴關係。這種自動連接簡化了複雜對象圖的配置,並促進了組件之間的鬆散耦合。

  4. 模塊組合: Autofac允許開發人員使用模塊來組織和封裝組件註冊。模塊作為相關註冊的邏輯容器,使得管理和維護具有多個組件的大型應用程序更加容易。

  5. 攔截和面向方面編程: Autofac提供對攔截和面向方面編程的支持。 (面向方面程式設計) 透過其攔截擴展。通過攔截,開發人員可以將橫切關注點如日誌記錄、緩存和安全應用於組件,而無需修改其實現。

  6. ASP.NET Core 和 .NET Core 整合:Autofac 與 .NET Core 和 ASP.NET Core 無縫整合,為現代 web 應用程式和微服務提供一流的依賴注入支持。它利用內建的服務提供者抽象來確保與 .NET 生態系統的兼容性和互操作性。

使用Autofac.NET的實際範例

讓我們探索一些實際範例來說明Autofac.NET的使用方法:

public class Program
{
    public static void Main()
    {
        // Setting up Autofac container
        var builder = new ContainerBuilder();
        // Registering types manually
        builder.RegisterType<MyService>().As<IMyService>();
        // Registering types using assembly scanning
        builder.RegisterAssemblyTypes(typeof(MyAssembly).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces();
        // Registering modules
        builder.RegisterModule(new MyModule());
        // Building the container
        var container = builder.Build();
        // Resolving dependencies
        using (var scope = container.BeginLifetimeScope())
        {
            var service = scope.Resolve<IMyService>();
            service.DoSomething();
        }
    }
}
public class Program
{
    public static void Main()
    {
        // Setting up Autofac container
        var builder = new ContainerBuilder();
        // Registering types manually
        builder.RegisterType<MyService>().As<IMyService>();
        // Registering types using assembly scanning
        builder.RegisterAssemblyTypes(typeof(MyAssembly).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces();
        // Registering modules
        builder.RegisterModule(new MyModule());
        // Building the container
        var container = builder.Build();
        // Resolving dependencies
        using (var scope = container.BeginLifetimeScope())
        {
            var service = scope.Resolve<IMyService>();
            service.DoSomething();
        }
    }
}
Public Class Program
	Public Shared Sub Main()
		' Setting up Autofac container
		Dim builder = New ContainerBuilder()
		' Registering types manually
		builder.RegisterType(Of MyService)().As(Of IMyService)()
		' Registering types using assembly scanning
		builder.RegisterAssemblyTypes(GetType(MyAssembly).Assembly).Where(Function(t) t.Name.EndsWith("Repository")).AsImplementedInterfaces()
		' Registering modules
		builder.RegisterModule(New MyModule())
		' Building the container
		Dim container = builder.Build()
		' Resolving dependencies
		Using scope = container.BeginLifetimeScope()
			Dim service = scope.Resolve(Of IMyService)()
			service.DoSomething()
		End Using
	End Sub
End Class
VB   C#

在本節中,我們展示了Autofac.NET用於依賴注入的實際應用。從手動註冊到程序集掃描以及模組化註冊,我們展現了Autofac在管理依賴性方面的靈活性。通過使用這些技術,開發人員可以簡化應用程式的依賴注入過程,提高可維護性和可擴展性。

使用 Autofac.NET 的好處

  1. 簡單和靈活性:Autofac 提供了一個簡單直觀的 API 來註冊和解析組件,使依賴注入的實施和維護變得容易。

  2. 可測試性和可維護性:通過促進鬆散耦合和依賴反轉,Autofac 增強了 .NET 應用程序的可測試性和可維護性,從而輕鬆進行單元測試和重構。

  3. 性能和可擴展性:Autofac 輕量且高效的運行時性能使其適合於高性能應用程序和具有大型物件圖的可擴展系統。

  4. 可擴展性和可定制性:Autofac 的可擴展架構允許開發人員通過自定義模塊、註冊源和中間件組件來擴展和自定義 Autofac 的行為,以滿足多樣化的應用需求。

  5. 社區和支持:Autofac 擁有活躍的開發者社區和全面的文檔,提供了出色的學習、故障排除和對框架貢獻的支持和資源。

Autofac 授權

Autofac 授權採用 MIT 授權,允許免費使用於開發和商業用途。

推介 Iron Software 的 IronPDF

Autofac .NET 6 (對開發人員的運作方式):圖1 - IronPDF 網頁

IronPDF 是一個強大的 C# PDF 庫,旨在為 .NET 專案中的 PDF 管理提供全面的解決方案。不論您的需求是建立、編輯、匯出、安全加密、載入或操作 PDF 文件,IronPDF 都具備您所需的工具。以下是一些其顯著的功能和應用:

主要功能

  • HTML 轉換成 PDF:輕鬆將 HTML 內容轉換為 PDF。可從 HTML、MVC、ASPX 和圖像生成 PDF。
  • PDF 管理:IronPDF 擁有超過 50 種功能,可以簽名、編輯和從 PDF 中提取內容,使得數位簽名和修改變得簡單。
  • 跨平台支持:適用於 C#、F# 和 VB.NET,IronPDF 能夠在多種 .NET 版本上運行,包括 .NET Core、.NET Standard 和 .NET Framework。它也適用於 Java、Node.js 和 Python。

兼容性和環境

  • .NET 版本: 支援 C#、VB.NET 和 F#。
  • 專案類型: 適用於網絡 (Blazor 和 WebForms),桌面 (WPF & MAUI),和控制台應用程式。
  • 應用環境:兼容 Windows、Linux、Mac、Docker、Azure、AWS 等。
  • IDE:無縫整合於 Microsoft Visual Studio 和 JetBrains Rider。
  • 作業系統與處理器:適用於 Windows、Mac 和 Linux (x64、x86、ARM).

PDF 標準與編輯

  • 相容性:支援各種 PDF 版本 (1.2 - 1.7), PDF/UA 和 PDF/A。
  • 自訂:設置 PDF 檔案的屬性、安全性和壓縮。
  • 元數據與結構:編輯元數據、修訂歷史和文檔結構。
  • 模板與設定:應用頁面模板、頁首、頁尾和頁面設定。

性能優化

  • 效率: 完全多線程和異步支持,以實現高效的PDF生成。
  • 優先: 專注於準確性、易用性和速度。

現在讓我們看看這兩個庫的實際例子。

使用 Autofac.NET 和 IronPDF 生成 PDF 文件

首先,讓我們創建一個 Visual Studio 主控台應用程式

Autofac .NET 6(對於開發人員的運作方式):圖2 - 創建Visual Studio控制台應用程式

請提供專案名稱和位置。

Autofac .NET 6(它如何為開發人員工作):圖3 - 配置專案詳情

接下來,選擇所需的 .NET 版本並點擊創建。

然後從 Visual Studio Package Manager 中的 NuGet 套件安裝 IronPDF 庫。

Autofac .NET 6(開發人員如何使用):圖4 - 安裝必要的 IronPDF 套件

從 Visual Studio 套件管理員的 NuGet 套件安裝 Autofac

Autofac .NET 6(對開發人員的工作原理):圖 5 - 安裝必要的 Autofac 套件

程式碼範例:Autofac 和 IronPDF

using Autofac;
using CacheManager.Core;
using IronPdf;
using System.Reflection;

namespace IronPdfDemos
{
    public class AutoFac
    {
        public static void Execute()
        {
            // Instantiate Cache and ChromePdfRenderer
            var renderer = new ChromePdfRenderer();
            var cache = CacheFactory.Build("ironPdfAutofac", settings =>
            {
                settings.WithDictionaryHandle();
            });

            // Prepare HTML content
            var content = "<h1>Demonstrate Autofac with IronPDF</h1>";
            content += "<p>This is an illustration of using Autofac for dependency injection and IronPDF for generating PDF documents.</p>";
            content += "<h2>Setting up Autofac container</h2>";

            // Setting up Autofac container
            var builder = new ContainerBuilder();
            content += "<p>var builder = new ContainerBuilder();</p>";

            content += "<h2>Registering types manually</h2>";
            // Registering types manually
            builder.RegisterType<MyService>().As<IMyService>();
            content += "<p>builder.RegisterType<MyService>().As<IMyService();</p>";

            content += "<h2>Registering types using assembly scanning</h2>";
            // Registering types using assembly scanning
            builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces();
            content += "<p>builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly).Where(t => t.Name.EndsWith(\"Repository\")).AsImplementedInterfaces();</p>";

            content += "<h2>Registering modules</h2>";
            // Registering modules
            builder.RegisterModule(new MyModule());
            content += "<p>builder.RegisterModule(new MyModule());</p>";

            content += "<h2>Building the container</h2>";
            // Building the container
            var container = builder.Build();
            content += "<p>var container = builder.Build();</p>";

            content += "<h2>Resolving dependencies</h2>";
            // Resolving dependencies
            using (var scope = container.BeginLifetimeScope())
            {
                var service = scope.Resolve<IMyService>();
                service.DoSomething();
            }
            content += "<p>var service = scope.Resolve<IMyService();</p>";

            // Create a PDF from the HTML string using C#
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("autofac.pdf");
            Console.WriteLine("We are done...");
            Console.ReadKey();
        }
    }

    internal interface IMyService
    {
        void DoSomething();
    }

    internal class MyModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // Register module dependencies here
        }
    }

    internal class MyService : IMyService
    {
        public void DoSomething()
        {
            Console.WriteLine("DoSomething");
        }
    }
}
using Autofac;
using CacheManager.Core;
using IronPdf;
using System.Reflection;

namespace IronPdfDemos
{
    public class AutoFac
    {
        public static void Execute()
        {
            // Instantiate Cache and ChromePdfRenderer
            var renderer = new ChromePdfRenderer();
            var cache = CacheFactory.Build("ironPdfAutofac", settings =>
            {
                settings.WithDictionaryHandle();
            });

            // Prepare HTML content
            var content = "<h1>Demonstrate Autofac with IronPDF</h1>";
            content += "<p>This is an illustration of using Autofac for dependency injection and IronPDF for generating PDF documents.</p>";
            content += "<h2>Setting up Autofac container</h2>";

            // Setting up Autofac container
            var builder = new ContainerBuilder();
            content += "<p>var builder = new ContainerBuilder();</p>";

            content += "<h2>Registering types manually</h2>";
            // Registering types manually
            builder.RegisterType<MyService>().As<IMyService>();
            content += "<p>builder.RegisterType<MyService>().As<IMyService();</p>";

            content += "<h2>Registering types using assembly scanning</h2>";
            // Registering types using assembly scanning
            builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces();
            content += "<p>builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly).Where(t => t.Name.EndsWith(\"Repository\")).AsImplementedInterfaces();</p>";

            content += "<h2>Registering modules</h2>";
            // Registering modules
            builder.RegisterModule(new MyModule());
            content += "<p>builder.RegisterModule(new MyModule());</p>";

            content += "<h2>Building the container</h2>";
            // Building the container
            var container = builder.Build();
            content += "<p>var container = builder.Build();</p>";

            content += "<h2>Resolving dependencies</h2>";
            // Resolving dependencies
            using (var scope = container.BeginLifetimeScope())
            {
                var service = scope.Resolve<IMyService>();
                service.DoSomething();
            }
            content += "<p>var service = scope.Resolve<IMyService();</p>";

            // Create a PDF from the HTML string using C#
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("autofac.pdf");
            Console.WriteLine("We are done...");
            Console.ReadKey();
        }
    }

    internal interface IMyService
    {
        void DoSomething();
    }

    internal class MyModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // Register module dependencies here
        }
    }

    internal class MyService : IMyService
    {
        public void DoSomething()
        {
            Console.WriteLine("DoSomething");
        }
    }
}
Imports Autofac
Imports CacheManager.Core
Imports IronPdf
Imports System.Reflection

Namespace IronPdfDemos
	Public Class AutoFac
		Public Shared Sub Execute()
			' Instantiate Cache and ChromePdfRenderer
			Dim renderer = New ChromePdfRenderer()
			Dim cache = CacheFactory.Build("ironPdfAutofac", Sub(settings)
				settings.WithDictionaryHandle()
			End Sub)

			' Prepare HTML content
			Dim content = "<h1>Demonstrate Autofac with IronPDF</h1>"
			content &= "<p>This is an illustration of using Autofac for dependency injection and IronPDF for generating PDF documents.</p>"
			content &= "<h2>Setting up Autofac container</h2>"

			' Setting up Autofac container
			Dim builder = New ContainerBuilder()
			content &= "<p>var builder = new ContainerBuilder();</p>"

			content &= "<h2>Registering types manually</h2>"
			' Registering types manually
			builder.RegisterType(Of MyService)().As(Of IMyService)()
			content &= "<p>builder.RegisterType<MyService>().As<IMyService();</p>"

			content &= "<h2>Registering types using assembly scanning</h2>"
			' Registering types using assembly scanning
			builder.RegisterAssemblyTypes(GetType(AutoFac).Assembly).Where(Function(t) t.Name.EndsWith("Repository")).AsImplementedInterfaces()
			content &= "<p>builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly).Where(t => t.Name.EndsWith(""Repository"")).AsImplementedInterfaces();</p>"

			content &= "<h2>Registering modules</h2>"
			' Registering modules
			builder.RegisterModule(New MyModule())
			content &= "<p>builder.RegisterModule(new MyModule());</p>"

			content &= "<h2>Building the container</h2>"
			' Building the container
			Dim container = builder.Build()
			content &= "<p>var container = builder.Build();</p>"

			content &= "<h2>Resolving dependencies</h2>"
			' Resolving dependencies
			Using scope = container.BeginLifetimeScope()
				Dim service = scope.Resolve(Of IMyService)()
				service.DoSomething()
			End Using
			content &= "<p>var service = scope.Resolve<IMyService();</p>"

			' Create a PDF from the HTML string using C#
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			' Export to a file or Stream
			pdf.SaveAs("autofac.pdf")
			Console.WriteLine("We are done...")
			Console.ReadKey()
		End Sub
	End Class

	Friend Interface IMyService
		Sub DoSomething()
	End Interface

	Friend Class MyModule
		Inherits Module

		Protected Overrides Sub Load(ByVal builder As ContainerBuilder)
			' Register module dependencies here
		End Sub
	End Class

	Friend Class MyService
		Implements IMyService

		Public Sub DoSomething() Implements IMyService.DoSomething
			Console.WriteLine("DoSomething")
		End Sub
	End Class
End Namespace
VB   C#

代码解释

让我们分解您提供的代码片段:

  1. ChromePdfRenderer 設置

    • 代碼初始化了一個 ChromePdfRenderer 實例用於渲染 PDF。
  2. HTML 內容準備

    • content 變量是一個 HTML 字符串,將用於生成 PDF。

    • 包含一個 <h1> 標籤,標題為 "Demonstrate Autofac with IronPDF"。
  3. 設置 Autofac 容器

    • 代碼創建了一個名為 builderContainerBuilder 實例。

    • 這是設置 Autofac 容器以進行依賴注入的第一步。
  4. 手動註冊類型

    • 註冊了一個類型 MyService 作為 IMyService 接口的實現。

    • 這允許 Autofac 在需要時解析依賴項。
  5. 使用程序集掃描註冊類型

    • 掃描包含 AutoFac 類的程序集。

    • 註冊名稱以 "Repository" 結尾的類型為其對應接口的實現。
  6. 註冊模塊

    • 註冊了一個名為 MyModule 的模塊。

    • 模塊允許將相關註冊分組。
  7. 構建容器

    • 使用 builder.Build 從註冊的組件構建容器。()方法。
  8. 解決依賴
  • 在生命週期範圍內 (使用 (```C# var scope = container.BeginLifetimeScope ```())``` ```), 它解析了一個IMyService` 的實例。

    • 在解析的服務上調用了 DoSomething 方法。
  1. PDF 生成

    • 使用 ChromePdfRenderer 從內容創建 PDF。

    • 生成的 PDF 保存為 "autofac.pdf"。

輸出

Autofac .NET 6(開發人員如何運作):圖6 - 前一個代碼範例輸出的PDF

IronPDF License

IronPDF 需要授權金鑰。將授權金鑰放置在 appSettings.json 文件中,如下所示。

{
  "IronPdf.License.LicenseKey": "The Key Here"
}

結論

總而言之,Autofac.NET 是一個穩定且功能豐富的 .NET 依賴注入容器,能夠幫助開發者構建模塊化、可維護且可擴展的應用程式。無論您正在開發桌面應用程式、網路服務還是雲原生解決方案,Autofac 都提供了一個可靠的基礎來管理依賴並促進 .NET 開發中的最佳實踐。

IronPDF 是一個多功能且功能豐富的庫,用於生成、編輯和讀取 PDF 文檔。通過使用 Iron Software 提供的 IronPDF 庫來讀取和生成 PDF 文檔,開發者可以獲得開發現代應用程式的先進技能。

< 上一頁
OpenTelemetry .NET(對開發人員的運作方式)
下一個 >
Papercut SMTP C#(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >