跳至頁尾內容
.NET 幫助

Microsoft.Extensions.DependencyInjection.NET 9(處理 PDF)

Microsoft.Extensions.DependencyInjection是 Microsoft .NET 提供的一個功能強大的函式庫,可促進依賴注入 (DI),這是一種軟體設計模式,可促進應用程式的鬆散耦合並提升可測性。 DI 通常使用 .NET Core 內建 DI 容器或 Autofac 和 Unity 等函式庫實作。 DI 涉及將依賴關係(類所需的物件)注入到類中,而不是由類來建立其依賴關係。 這通常是透過建構子、方法或屬性注入來完成。

Microsoft.Extensions.DependencyInjection .NET 6 (Working With PDF):圖 1 - Microsoft.Extensions.DependencyInjectionName 文件

依賴注入容器

1.服務註冊:相依性在 DI 容器中註冊,通常位於應用程式的組成根目錄。 這些註冊規定容器應如何建立和管理相依性。

2.依賴解析:當元件請求依賴時,DI 容器會透過建立使用擴充方法的註冊類型實例來解析依賴。

依賴注入的類型

  • 建構子注入:透過類別的建構子提供註冊服務,這是最常見也是最推薦的 DI 形式。
  • 方法注入:服務被解析並作為參數傳送給方法。
  • Property Injection:單件服務或具有範圍生命週期的服務可以指定給類的屬性。 然而,這種方法較不常見,而且常被認為不如構建器注入,因為它可能會引入隱藏的依賴關係。

瞭解依賴注入 (DI) 的生命期:範圍、暫態和單體。

1.作用域:作用域依賴在每個請求或生命週期作用域中建立一次,這表示容器在單一請求或作業中提供相同的實體。 這種一致性在 Web 應用程式中特別有用,因為範圍相依性有助於在整個 Web 請求中維持穩定的相依性。 2.暫態:暫態依賴每次從容器請求時都會被實體化。 這意味著只要有需要,就會產生新的暫態依賴實例。 通常,瞬態依賴用於輕量級、無狀態的服務或元件。 3.單件:單件相依性僅實體化一次,並在應用程式的整個生命週期中共用。這可確保在應用程式的整個生命週期中,所有請求都會使用相同的單一依賴實體。 對於需要在整個應用程式中普遍存取的有狀態服務或元件,通常會使用單件式相依性。

安裝Microsoft.Extensions.DependencyInjection套件

若要開始在 .NET Core 專案中使用依賴注入,您首先需要安裝 Microsoft.Extensions.DependencyInjection 套件。 可透過 Visual Studio 中的 NuGet Package Manager Console 使用下列指令完成:

Install-Package Microsoft.Extensions.DependencyInjection

螢幕快照

Microsoft.Extensions.DependencyInjection .NET 6 (Working With PDF):圖 2 - 輸入命令到終端機以安裝套件

範例:基本的依賴注入

在本範例中,讓我們建立一個範例應用程式 (主控台應用程式),其中我們將運用服務提供者來解析服務,並將它們注入我們的程式中。

using Microsoft.Extensions.DependencyInjection;
using System;

// Define a service interface
public interface IMessageService
{
    void SendMessage(string message);
}

// Implement the service interface
public class ConsoleMessageService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine(message); // Output the message to the console
    }
}
using Microsoft.Extensions.DependencyInjection;
using System;

// Define a service interface
public interface IMessageService
{
    void SendMessage(string message);
}

// Implement the service interface
public class ConsoleMessageService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine(message); // Output the message to the console
    }
}
$vbLabelText   $csharpLabel

該程式碼片段建立了一個用於傳送訊息的介面 IMessageService ,就像是一份訊息傳送方式的合約。 ConsoleMessageService 類透過使用 Console.WriteLine 傳送訊息來實作此介面。 這樣的分離使得傳送訊息的概念可以獨立於訊息的傳送方式而改變,讓系統變得更靈活、更易於管理。

class Program
{
    static void Main(string[] args)
    {
        // Create a service provider
        var serviceProvider = new ServiceCollection()
            // Register the service implementation
            .AddTransient<IMessageService, ConsoleMessageService>()
            .BuildServiceProvider();

        // Resolve the service
        var messageService = serviceProvider.GetRequiredService<IMessageService>();

        // Use the service to send a message
        messageService.SendMessage("Hello, From Dependency Injection!");
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Create a service provider
        var serviceProvider = new ServiceCollection()
            // Register the service implementation
            .AddTransient<IMessageService, ConsoleMessageService>()
            .BuildServiceProvider();

        // Resolve the service
        var messageService = serviceProvider.GetRequiredService<IMessageService>();

        // Use the service to send a message
        messageService.SendMessage("Hello, From Dependency Injection!");
    }
}
$vbLabelText   $csharpLabel

此代碼設定了一個 serviceProvider 來管理服務。 它將 ConsoleMessageService 註冊為 IMessageService 的實作,使其可在任何需要的地方注入。 然後 Main 方法會從 serviceProvider 擷取 IMessageService 的實體,並使用它傳送訊息到控制台。

輸出:程式列印字串訊息 "Hello, From Dependency Injection!"

Microsoft.Extensions.DependencyInjection .NET 6 (Working With PDF):圖 3 - 上述程式碼的控制台輸出

IronPDF:C# PDF 函式庫

IronPDF是一個功能強大的 C# 函式庫,可簡化複雜的 PDF 產生過程,提供廣泛的 PDF 操作功能,包括從 HTML 產生 PDF的能力、操作將文字新增至 PDF使用影像編輯 PDF、建立安全的文件等等。

Microsoft.Extensions.DependencyInjection .NET 6 (Working With PDF):圖 4 - Microsoft.Extensions.DependencyInjection C# 範例 (如何為開發人員工作):圖 2 - IronPDF

使用 IronPDF 與依賴注入。

若要利用 Microsoft.Extensions.DependencyInjection 的依賴注入功能和擴充方法,將 IronPDF 函式庫整合到 .NET Core 應用程式中,您可以採取下列步驟:

1.建立一個介面來定義您的 PDF 產生服務。 2.執行介面。 3.利用擴充方法在依賴注入容器中註冊服務。 4.根據需要將服務注入您的應用程式。

定義介面

建立一個介面來定義您的 PDF 產生服務。

public interface IPdfService
{
    void GeneratePdf(string baseUrl, string query, string filePath);
}
public interface IPdfService
{
    void GeneratePdf(string baseUrl, string query, string filePath);
}
$vbLabelText   $csharpLabel

實作介面

使用 IronPDF 實作介面以建立 PDF 檔案。

using IronPdf;
using System;
using System.Web;

// Implement the PDF generation interface
public class IronPdfService : IPdfService
{
    public void GeneratePdf(string baseUrl, string query, string filePath)
    {
        License.LicenseKey = "Your-License-Key"; // Set the IronPDF license key
        string encodedQuery = HttpUtility.UrlEncode(query); // Encode the query string
        string fullUrl = $"{baseUrl}?query={encodedQuery}"; // Construct the full URL
        var renderer = new ChromePdfRenderer(); // Create a PDF renderer
        var pdf = renderer.RenderUrlAsPdf(fullUrl); // Render the PDF from the URL
        pdf.SaveAs(filePath); // Save the PDF to the specified file path
        Console.WriteLine($"PDF successfully created from: {fullUrl}");
        Console.WriteLine($"Saved to: {filePath}");
    }
}
using IronPdf;
using System;
using System.Web;

// Implement the PDF generation interface
public class IronPdfService : IPdfService
{
    public void GeneratePdf(string baseUrl, string query, string filePath)
    {
        License.LicenseKey = "Your-License-Key"; // Set the IronPDF license key
        string encodedQuery = HttpUtility.UrlEncode(query); // Encode the query string
        string fullUrl = $"{baseUrl}?query={encodedQuery}"; // Construct the full URL
        var renderer = new ChromePdfRenderer(); // Create a PDF renderer
        var pdf = renderer.RenderUrlAsPdf(fullUrl); // Render the PDF from the URL
        pdf.SaveAs(filePath); // Save the PDF to the specified file path
        Console.WriteLine($"PDF successfully created from: {fullUrl}");
        Console.WriteLine($"Saved to: {filePath}");
    }
}
$vbLabelText   $csharpLabel

註冊服務

在您的 Program.cs 類中,配置依賴注入:

builder.Services.AddSingleton<IPdfService, IronPdfService>();
builder.Services.AddSingleton<IPdfService, IronPdfService>();
$vbLabelText   $csharpLabel

此設定透過使用 IronPdfService 實作 IPdfService 介面來解決相依性問題,為 PDF 生成建立單一服務類型。 然後在整個應用程式中引用,確保產生 PDF 的功能一致。

用途

IPdfService 注入您的控制器或服務,並使用它:

public class MyController : Controller
{
    private readonly IPdfService _pdfService;

    public MyController(IPdfService pdfService)
    {
        _pdfService = pdfService;
    }

    public IActionResult GeneratePdf()
    {
        string baseUrl = "https://ironpdf.com/";
        string query = "Hello World from IronPDF !";
        string filePath = "Demo.pdf";

        // Use the injected PDF service to generate a PDF
        _pdfService.GeneratePdf(baseUrl, query, filePath);

        return View();
    }
}
public class MyController : Controller
{
    private readonly IPdfService _pdfService;

    public MyController(IPdfService pdfService)
    {
        _pdfService = pdfService;
    }

    public IActionResult GeneratePdf()
    {
        string baseUrl = "https://ironpdf.com/";
        string query = "Hello World from IronPDF !";
        string filePath = "Demo.pdf";

        // Use the injected PDF service to generate a PDF
        _pdfService.GeneratePdf(baseUrl, query, filePath);

        return View();
    }
}
$vbLabelText   $csharpLabel

此設定可確保 IronPdfService 由 Microsoft Extensions Dependency Injection 容器建立與管理。 您可以透過提供 IPdfService 介面的替代實作,毫不費力地取代預設的 PDF 生成服務,而完全不需要更改消耗的程式碼。

PDF 檔案的螢幕截圖

Microsoft.Extensions.DependencyInjection .NET 6 (Working With PDF):圖 5 - 結合 IronPDF 使用 Microsoft Extensions 依赖注入容器的輸出範例

結論

Microsoft.Extensions.DependencyInjection是.NET 6中實施依賴注入的強大工具,可促進應用程式的鬆散耦合並提升可測性。 透過整合 IronPDF 這個功能豐富的 C# 函式庫,開發人員可以輕鬆地以最少的工作量產生全面的 PDF 文件。 可取得 IronPDF 的授權

常見問題解答

Microsoft.Extensions.DependencyInjection 在 .NET 6 中扮演什麼角色?

.NET 6 中的 Microsoft.Extensions.DependencyInjection 用於實現依賴注入,這是一種設計模式,它透過使用 DI 容器來管理服務生命週期和依賴項,從而幫助創建鬆散耦合的應用程式。

依賴注入如何提高應用程式的可測試性?

依賴注入透過允許將依賴項注入到類別中來增強可測試性,從而更容易在測試期間替換模擬物件而不是實際實現。

在.NET應用程式中使用依賴注入有哪些好處?

在 .NET 應用程式中使用依賴注入的好處包括提高程式碼可維護性、可擴充性,以及在執行時間輕鬆管理和配置依賴項的能力。

如何在.NET Core應用程式中實現依賴注入?

在 .NET Core 應用程式中,依賴注入是透過在應用程式啟動期間配置 DI 容器中的服務,並根據需要將它們注入到建構函數或方法中來實現的。

如何在 .NET Core 應用程式中將 HTML 轉換為 PDF?

在 .NET Core 應用程式中,您可以使用 IronPDF 的方法將 HTML 轉換為 PDF,例如使用RenderHtmlAsPdf處理 HTML 字串,或使用RenderHtmlFileAsPdf處理 HTML 檔案。

依賴注入中服務的生命週期有哪些不同,它們如何影響應用程式的行為?

依賴注入中的服務生命週期分為作用域服務、瞬態服務和單例服務。作用域服務每次要求只創建一次,瞬態服務每次被要求時都會創建,而單例服務創建一次後即可在整個應用程式中共享。

如何使用依賴注入將 C# PDF 庫整合到 .NET Core 專案中?

要使用依賴注入將 IronPDF 等 C# PDF 庫整合到 .NET Core 專案中,您需要為 PDF 服務建立一個接口,實現它,在 DI 容器中註冊該服務,並根據需要將其註入到您的類別中。

如何安裝 Microsoft.Extensions.DependencyInjection 套件?

可以使用 Visual Studio 中的 NuGet 套件管理器控制台,透過下列命令安裝Install-Package Microsoft.Extensions.DependencyInjection

如何將 IronPDF 與依賴注入結合使用來產生 PDF 文件?

IronPDF 可以透過設定 PDF 服務介面、使用 IronPDF 方法實現該介面並將其註冊到依賴注入容器中來與依賴注入 (DI) 結合使用。之後,即可注入該服務並使其能夠根據 URL 或 HTML 內容產生 PDF 文件。

在不修改使用程式碼的情況下,能否在依賴注入 (DI) 設定中取代 C# PDF 函式庫?

是的,您可以透過實作用於 PDF 服務的介面的替代方案,在 DI 設定中取代 C# PDF 庫,從而允許您在不更改使用程式碼的情況下切換庫。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。