跳過到頁腳內容
.NET幫助

簡單注入器 C# (如何為開發人員運作)

在開發 .NET 應用程式時,維持可管理且乾淨的程式碼是至關重要的。 依賴注入 (DI) 是一種設計模式,可促進類別間的松散耦合,增強可測試性和可維護性。 Simple Injector 是一個廣受歡迎的 DI 函式庫,以其效能、彈性和易用性而聞名。 它可讓開發人員使用最少的設定來管理相依性。

IronPDF 是一個功能強大的 .NET 函式庫,用於建立、閱讀和修改 PDF 文件。 它支援廣泛的功能,包括將 HTML 轉換為 PDF 和處理 PDF,因此是需要動態 PDF 產生和處理的應用程式的理想選擇。

本教學說明如何整合 IronPDF 以進行無縫 PDF 創作,並使用 Simple Injector 管理 C# 應用程式內的依賴關係。 透過結合這兩種強大的工具,開發人員可以建構出功能更強、可擴充、可維護且更有效率的應用程式,不論是簡單的主控台應用程式或是複雜的企業系統。

什麼是 C# 中的 [Simple Injector](https://docs.simpleinjector.org/en/latest/quickstart.html)?

對於 .NET 應用程式,Simple Injector 是一個可靠且容易使用的依賴注入 (DI) 函式庫。 憑藉其強大且適應性強的控制物件生命週期和依賴關係的功能,其設計簡明易懂。 以下是 Simple Injector 提供的一些主要功能:

Simple Injector C# (How It Works For Developers):圖 1 - 簡單注入器首頁

Simple Injector 的主要功能

簡單易用

Simple Injector 具有直觀的 API,即使是不熟悉構成器注入的開發人員也可以輕鬆配置和使用。

  • Minimal Configuration: 由於 DI 的設定簡單直接,因此開發人員只需使用最少的模板程式碼,即可將 DI 包含在其應用程式中。

效能

  • 高速:依賴解析快速且有效率,使得 Simple Injector 適合以毫秒計算的高效能應用程式。

彈性

  • 不同的生命週期管理:它支援各種不同的生命週期,例如暫態、作用域和單件物件生命週期,讓開發人員可以根據自己的需求選擇最佳的生命週期管理方式。

  • 進階方案:支援進階 DI 模式,例如:基於裝飾器的模式和屬性注入。

綜合文件

Simple Injector 包含詳細且組織良好的說明文件、程式碼範例和最佳實務,可協助開發人員瞭解其功能。

安全與診斷

  • 驗證:該函式庫提供驗證步驟,有助於在開發過程的早期發現配置錯誤。

  • 診斷服務:提供診斷服務以找出並解決常見的 DI 問題,改善應用程式的可靠性。

Creating and Configuring Simple Injector in C#

以下步驟說明如何在 C# 應用程式中設定和配置 Simple Injector:

建立新專案

從建立新的 .NET 主控台應用程式開始。 開啟終端並執行下列指令:

dotnet new console -n SimpleInjectorExample
cd SimpleInjectorExample
dotnet new console -n SimpleInjectorExample
cd SimpleInjectorExample
SHELL

安裝 Simple Injector 套件

接下來,使用 NuGet 將 Simple Injector 套件新增至您的專案:

dotnet add package SimpleInjector
dotnet add package SimpleInjector
SHELL

設定依賴注入容器

開啟 Program.cs 檔案來設定 Simple Injector 容器。 以下是設定方法:

using SimpleInjector;
using System;

namespace SimpleInjectorExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the Simple Injector container
            var container = new Container();

            // Register your types
            container.Register<IUserService, UserService>(Lifestyle.Singleton);

            // Optionally verify the container configuration
            container.Verify();

            // Resolve an instance of IUserService and use it
            var userService = container.GetInstance<IUserService>();
            userService.ProcessUser();

            Console.WriteLine("Dependency Injection with Simple Injector is set up!");
        }
    }

    // Define the service interface
    public interface IUserService
    {
        void ProcessUser();
    }

    // Implement the service
    public class UserService : IUserService
    {
        public void ProcessUser()
        {
            Console.WriteLine("Processing user...");
        }
    }
}
using SimpleInjector;
using System;

namespace SimpleInjectorExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the Simple Injector container
            var container = new Container();

            // Register your types
            container.Register<IUserService, UserService>(Lifestyle.Singleton);

            // Optionally verify the container configuration
            container.Verify();

            // Resolve an instance of IUserService and use it
            var userService = container.GetInstance<IUserService>();
            userService.ProcessUser();

            Console.WriteLine("Dependency Injection with Simple Injector is set up!");
        }
    }

    // Define the service interface
    public interface IUserService
    {
        void ProcessUser();
    }

    // Implement the service
    public class UserService : IUserService
    {
        public void ProcessUser()
        {
            Console.WriteLine("Processing user...");
        }
    }
}
Imports SimpleInjector
Imports System

Namespace SimpleInjectorExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create the Simple Injector container
			Dim container As New Container()

			' Register your types
			container.Register(Of IUserService, UserService)(Lifestyle.Singleton)

			' Optionally verify the container configuration
			container.Verify()

			' Resolve an instance of IUserService and use it
			Dim userService = container.GetInstance(Of IUserService)()
			userService.ProcessUser()

			Console.WriteLine("Dependency Injection with Simple Injector is set up!")
		End Sub
	End Class

	' Define the service interface
	Public Interface IUserService
		Sub ProcessUser()
	End Interface

	' Implement the service
	Public Class UserService
		Implements IUserService

		Public Sub ProcessUser() Implements IUserService.ProcessUser
			Console.WriteLine("Processing user...")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel
  • var container = new Container();:建立 Simple Injector 容器類別的實例。

  • container.Register<IUserService, UserService>(Lifestyle.Singleton);:IUserService 介面及其實作 UserService 註冊為單例。 其他生活方式,例如 Transient 或 Scoped,也可根據需求加以運用。

  • container.Verify();:驗證容器配置,檢查註冊的有效性。 此步驟是可選的,但有助於及早發現配置錯誤。

  • var userService = container.GetInstance<IUserService>();:從容器解析 IUserService 的實例。

  • userService.ProcessUser();:呼叫已解析實例上的 ProcessUser 方法。

若要執行應用程式,請在您的終端執行下列指令:

dotnet run
dotnet run
SHELL

Simple Injector C# (How It Works For Developers):圖 2 - 控制台輸出

開始

在 C# 應用程式中整合 Simple Injector 與 IronPDF,包括安裝所需的套件、為相依性注入模式設定 Simple Injector,以及使用 IronPDF 製作 PDF。 以下是幫助您入門的步驟。

什麼是 Iron Software 的 [IronPDF](/)?

IronPDF 是一個功能強大的 .NET 函式庫,專為在 C# 應用程式中建立、閱讀和修改 PDF 文件而設計。 它可讓開發人員透過程式從 HTML、CSS 和 JavaScript 內容製作高品質、可列印的文件。 一些關鍵功能包括水印、新增頁首和頁腳、合併和分割 PDF,以及將 HTML 轉換為 PDF。 IronPDF 支援 .NET Framework 和 .NET Core,因此適用範圍廣泛。

由於 PDF 的文件詳盡且易於整合,開發人員可以快速地將 PDF 功能整合到他們的專案中。 IronPDF 還能夠輕鬆處理複雜的版面設計和樣式,確保生成的 PDF 貼近原始 HTML。

Simple Injector C# (How It Works For Developers):圖 3 - IronPDF:C# PDF Library

IronPDF 的特點

從 HTML 產生 PDF

  • 可將 HTML、CSS 和 JavaScript 轉換為 PDF,支援媒體查詢和回應式設計,對動態造型 PDF 文件、報告和發票非常有用。

PDF編輯

  • 允許從現有的 PDF 中新增和移除文字、圖片和其他內容,將多個 PDF 合併為一個,或將 PDF 分割為獨立的文件。 它支援加入水印、註解、頁首及頁尾。

PDF 轉檔

  • 提供各種檔案類型 (如 Word、Excel 和影像) 至 PDF 的轉換,以及 PDF 至影像 (PNG、JPEG 等) 的轉換。

效能與可靠性

  • 在工業環境中,高效能管理大型文件的高效能和可靠性是可取的。

安裝 IronPDF

要獲得在 .NET 應用程式中使用 PDF 所需的工具,請安裝 IronPDF 套件。

Install-Package IronPdf

使用 IronPDF 設定依賴注入容器

開啟 Program.cs 檔案,設定 Simple Injector 容器以與 IronPDF 一起使用:

using SimpleInjector;
using System;
using IronPdf;

namespace SimpleInjectorIronPDFExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the Simple Injector container
            var container = new Container();

            // Register your types
            container.Register<IPdfService, PdfService>(Lifestyle.Singleton);

            // Verify the container configuration
            container.Verify();

            // Resolve an instance of IPdfService and use it
            var pdfService = container.GetInstance<IPdfService>();
            pdfService.GeneratePdf("Hello, world!");

            Console.WriteLine("PDF generation complete!");
        }
    }

    // Define the PDF service interface
    public interface IPdfService
    {
        void GeneratePdf(string content);
    }

    // Implement the PDF service
    public class PdfService : IPdfService
    {
        public void GeneratePdf(string content)
        {
            // Create a new HtmlToPdf renderer
            var renderer = new HtmlToPdf();

            // Render the HTML content as a PDF
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Save the PDF to a file
            pdf.SaveAs("output.pdf");
        }
    }
}
using SimpleInjector;
using System;
using IronPdf;

namespace SimpleInjectorIronPDFExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the Simple Injector container
            var container = new Container();

            // Register your types
            container.Register<IPdfService, PdfService>(Lifestyle.Singleton);

            // Verify the container configuration
            container.Verify();

            // Resolve an instance of IPdfService and use it
            var pdfService = container.GetInstance<IPdfService>();
            pdfService.GeneratePdf("Hello, world!");

            Console.WriteLine("PDF generation complete!");
        }
    }

    // Define the PDF service interface
    public interface IPdfService
    {
        void GeneratePdf(string content);
    }

    // Implement the PDF service
    public class PdfService : IPdfService
    {
        public void GeneratePdf(string content)
        {
            // Create a new HtmlToPdf renderer
            var renderer = new HtmlToPdf();

            // Render the HTML content as a PDF
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Save the PDF to a file
            pdf.SaveAs("output.pdf");
        }
    }
}
Imports SimpleInjector
Imports System
Imports IronPdf

Namespace SimpleInjectorIronPDFExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create the Simple Injector container
			Dim container As New Container()

			' Register your types
			container.Register(Of IPdfService, PdfService)(Lifestyle.Singleton)

			' Verify the container configuration
			container.Verify()

			' Resolve an instance of IPdfService and use it
			Dim pdfService = container.GetInstance(Of IPdfService)()
			pdfService.GeneratePdf("Hello, world!")

			Console.WriteLine("PDF generation complete!")
		End Sub
	End Class

	' Define the PDF service interface
	Public Interface IPdfService
		Sub GeneratePdf(ByVal content As String)
	End Interface

	' Implement the PDF service
	Public Class PdfService
		Implements IPdfService

		Public Sub GeneratePdf(ByVal content As String) Implements IPdfService.GeneratePdf
			' Create a new HtmlToPdf renderer
			Dim renderer = New HtmlToPdf()

			' Render the HTML content as a PDF
			Dim pdf = renderer.RenderHtmlAsPdf(content)

			' Save the PDF to a file
			pdf.SaveAs("output.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

本 C# 程式碼示範如何將用於 PDF 建立的 IronPDF 與用於依賴注入的 Simple Injector 整合到 .NET 主控台應用程式中。 建立了一個簡單的注入器容器來處理依賴項,將 IPdfService 及其實作 PdfService 註冊為單例,以確保在整個應用程式中使用單一實例。 容器配置經過驗證,以便及早發現任何註冊問題。

Simple Injector C# (How It Works For Developers):圖 4 - 控制台輸出

Main 方法中,從容器中解析出 IPdfService 的實例,並呼叫其 GeneratePdf 方法。 此方法使用 IronPDF 的 HtmlToPdf 類別從提供的 HTML 字串產生 PDF,並將產生的文件儲存為 output.pdf。 指示 PDF 生成完成的控制台訊息標示著作業的結束。 本設定說明如何有效管理相依性,並使用 IronPDF 以結構化、可維護的方式建立動態 PDF 文件。

Simple Injector C# (How It Works For Developers):圖 5 - PDF 輸出範例

結論

在 C# 應用程式中整合 Simple Injector 與 IronPDF,可有效管理相依性並簡化動態 PDF 的建立。 Simple Injector 提供強大的效能和直接的依賴注入 API,確保可維護且鬆散耦合的元件。 搭配 IronPDF 強大的 PDF 生成功能,開發人員可以輕鬆地將 HTML 內容轉換成高品質的 PDF 文件。 透過利用基於屬性的組態方法和了解這些工具,開發人員可以簡化管理依賴關係和滿足功能需求的方法。

這種組合不僅增強了程式碼的可管理性和可擴展性,還簡化了 PDF 創建等複雜的任務。 按照本教學中概述的步驟,您可以利用 Simple Injector 和 IronPDF 建立一個強大的架構,從而使 .NET 應用程式更具結構化、適應性和功能強大。

最後,請考慮將 IronPDF 和 explore more products from Iron Software 加入您的 .NET 程式設計武器庫,以處理條碼、產生 PDF、執行 OCR 並與 Excel 連線。 了解更多關於 IronPDF 的功能,透過將其功能與 Iron Software 的靈活系統和套件集成,實現高效開發,起價為 $999。

明確的授權選項可讓開發人員量身打造最適合其專案特定需求的模式,使他們能夠以容易整合、有效且透明的方式解決一系列問題。

常見問題解答

怎樣在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。此外,IronPDF 還支援使用 RenderHtmlFileAsPdf 方法直接轉換 HTML 文件。

什麼是 C# 中的 Simple Injector,它有什麼用處?

Simple Injector 是一個適用於 .NET 應用程序的簡單依賴注入庫。它有助於高效管理對象的生命周期和依賴關係,增強代碼的簡單性和性能。

如何在 C# 專案中設置 Simple Injector?

要設置 Simple Injector,您需要通過 NuGet 將 Simple Injector 套件添加到您的 .NET 專案中,在 Program.cs 文件中配置容器,註冊您的類型,並驗證容器配置的準確性。

使用 Simple Injector 與 IronPDF 的好處是什麼?

將 Simple Injector 與 IronPDF 相結合,使代碼的可管理性和可擴展性更好。它簡化了 .NET 應用程序中生成 PDF 的過程,確保代碼基礎更易維護且鬆耦合。

依賴注入庫如何改善 C# 應用中的 PDF 生成?

通過將 Simple Injector 與 IronPDF 結合使用,開發人員可以輕鬆管理依賴關係並簡化生成 PDF 的過程。這種整合確保了組件鬆耦合,提高了應用程序的可維護性和可擴展性。

.NET PDF 庫如 IronPDF 提供了哪些功能?

IronPDF 提供了廣泛的功能,包括將 HTML 轉換為 PDF、編輯現有的 PDF,並支援複雜的佈局。它確保生成的 PDF 與原始 HTML 內容緊密匹配。

如何排除將 Simple Injector 與 PDF 庫集成時的常見問題?

確保所有服務都正確註冊在 Simple Injector 容器中。驗證容器正確配置,且依賴關係在運行時得到解決。利用 Simple Injector 提供的診斷服務進行進一步的故障排除。

在 .NET 應用程序中從 HTML生成 PDF 涉及哪些步驟?

要在 .NET 應用程序中使用 IronPDF 從 HTML 生成 PDF,安裝 IronPDF 套件,配置 Simple Injector 容器進行依賴注入,並使用 IronPDF 的 HtmlToPdf 渲染器將 HTML 內容轉換為 PDF 文檔。

Simple Injector 提供哪些生活方式管理選項?

Simple Injector 提供多種生活方式管理選項,例如暫時性、單例和作用域生命周期,允許開發人員控制物件在應用程序中被實例化的方式和時間。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我