在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在 .NET 開發領域中,有效管理依賴對於構建可擴展、可維護和可測試的應用程序至關重要。依賴注入 (數字輸入) 容器透過實現控制反轉在達成這些目標中扮演了關鍵角色 (控制反轉) 原則。在眾多通用託管機制庫中,Autofac 脫穎而出,成為一個功能豐富且可擴展的 .NET 框架。
在本文中,我們將開始探索 Autofac .NET 6,揭示其功能和優勢,並展示其使用的實際示例。在本文的後半部分,我們將學習 IronPDF,這是 Iron Software 提供的一個 PDF 生成庫。我們還會展示一個 Autofac.NET 和 IronPDF 一起使用的實際案例。
Autofac 是一個開源的 .NET IoC 容器,它為依賴注入和元件註冊在像 Web API 這樣的應用程式中提供了全面的支援。由 Nicholas Blumhardt 開發並由專門的社群維護,Autofac 提供了一個健全且靈活的解決方案,用於管理物件生命週期、解決依賴關係和組合應用程式元件。
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
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
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
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
靈活的組件註冊: Autofac允許開發人員使用各種註冊技術來註冊組件,包括手動註冊、程序集掃描和基於屬性的註冊。這種靈活性使得組件實例化和配置的控制更加精細。
生命周期管理: Autofac支持各種對象生命周期範圍,包括單例、每個依賴實例、每個生命周期範圍實例和每個請求實例。對對象生命周期的這種精細控制確保了資源的有效利用,並防止了長期運行應用程序中的內存泄漏。
自動解決依賴關係: Autofac根據註冊的組件註冊和它們的依賴關係自動解決依賴關係。這種自動連接簡化了複雜對象圖的配置,並促進了組件之間的鬆散耦合。
模塊組合: Autofac允許開發人員使用模塊來組織和封裝組件註冊。模塊作為相關註冊的邏輯容器,使得管理和維護具有多個組件的大型應用程序更加容易。
攔截和面向方面編程: Autofac提供對攔截和面向方面編程的支持。 (面向方面程式設計) 透過其攔截擴展。通過攔截,開發人員可以將橫切關注點如日誌記錄、緩存和安全應用於組件,而無需修改其實現。
讓我們探索一些實際範例來說明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
在本節中,我們展示了Autofac.NET用於依賴注入的實際應用。從手動註冊到程序集掃描以及模組化註冊,我們展現了Autofac在管理依賴性方面的靈活性。通過使用這些技術,開發人員可以簡化應用程式的依賴注入過程,提高可維護性和可擴展性。
簡單和靈活性:Autofac 提供了一個簡單直觀的 API 來註冊和解析組件,使依賴注入的實施和維護變得容易。
可測試性和可維護性:通過促進鬆散耦合和依賴反轉,Autofac 增強了 .NET 應用程序的可測試性和可維護性,從而輕鬆進行單元測試和重構。
性能和可擴展性:Autofac 輕量且高效的運行時性能使其適合於高性能應用程序和具有大型物件圖的可擴展系統。
可擴展性和可定制性:Autofac 的可擴展架構允許開發人員通過自定義模塊、註冊源和中間件組件來擴展和自定義 Autofac 的行為,以滿足多樣化的應用需求。
Autofac 授權採用 MIT 授權,允許免費使用於開發和商業用途。
IronPDF 是一個強大的 C# PDF 庫,旨在為 .NET 專案中的 PDF 管理提供全面的解決方案。不論您的需求是建立、編輯、匯出、安全加密、載入或操作 PDF 文件,IronPDF 都具備您所需的工具。以下是一些其顯著的功能和應用:
現在讓我們看看這兩個庫的實際例子。
首先,讓我們創建一個 Visual Studio 主控台應用程式
請提供專案名稱和位置。
接下來,選擇所需的 .NET 版本並點擊創建。
然後從 Visual Studio Package Manager 中的 NuGet 套件安裝 IronPDF 庫。
從 Visual Studio 套件管理員的 NuGet 套件安裝 Autofac
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
让我们分解您提供的代码片段:
ChromePdfRenderer 設置:
ChromePdfRenderer
實例用於渲染 PDF。HTML 內容準備:
content
變量是一個 HTML 字符串,將用於生成 PDF。
<h1>
標籤,標題為 "Demonstrate Autofac with IronPDF"。設置 Autofac 容器:
代碼創建了一個名為 builder
的 ContainerBuilder
實例。
手動註冊類型:
註冊了一個類型 MyService
作為 IMyService
接口的實現。
使用程序集掃描註冊類型:
掃描包含 AutoFac
類的程序集。
註冊模塊:
註冊了一個名為 MyModule
的模塊。
構建容器:
builder.Build
從註冊的組件構建容器。()方法。在生命週期範圍內 (使用 (```C# var scope = container.BeginLifetimeScope ```())``` ```), 它解析了一個
IMyService` 的實例。
DoSomething
方法。PDF 生成:
使用 ChromePdfRenderer
從內容創建 PDF。
IronPDF 需要授權金鑰。將授權金鑰放置在 appSettings.json
文件中,如下所示。
{
"IronPdf.License.LicenseKey": "The Key Here"
}
總而言之,Autofac.NET 是一個穩定且功能豐富的 .NET 依賴注入容器,能夠幫助開發者構建模塊化、可維護且可擴展的應用程式。無論您正在開發桌面應用程式、網路服務還是雲原生解決方案,Autofac 都提供了一個可靠的基礎來管理依賴並促進 .NET 開發中的最佳實踐。
IronPDF 是一個多功能且功能豐富的庫,用於生成、編輯和讀取 PDF 文檔。通過使用 Iron Software 提供的 IronPDF 庫來讀取和生成 PDF 文檔,開發者可以獲得開發現代應用程式的先進技能。