Microsoft.Extensions .DependencyInjection .NET 9(PDF使用說明)
Microsoft.Extensions.DependencyInjection 是 Microsoft .NET 提供的一個強大的程式庫,用於促進依賴注入 (DI),這是一種軟體設計模式,促進鬆耦合並增強應用程式的可測試性。 DI 通常使用.NET Core 內建的 DI 容器或像 Autofac 和 Unity 這樣的程式庫來實現。 DI 涉及將依賴項(類所需的物件)注入到類中,而不是類自己建立其依賴項。 這通常通過構造函式、方法或屬性注入來完成。

依賴注入容器
-
服務註冊:依賴項會在應用程式的組成根中註冊到 DI 容器中。 這些註冊指定容器應如何建立和管理依賴項。
- 依賴解析:當元件請求依賴項時,DI 容器通過建立使用擴展方法的已註冊型別的實例來解析依賴項。
依賴注入的型別
- 構造函式注入:註冊的服務通過其構造函式提供給類,這是最常見且建議的 DI 形式。
- 方法注入:服務被解析並作為參數傳遞給方法。
- 屬性注入:單例服務或具有範圍生命週期的服務可以被分配給類屬性。 然而,這種方法不太常見,且經常被認為不如構造函式注入,因為它可能引入隱藏的依賴項。
理解依賴注入 (DI) 的生命週期:範圍、瞬態和單例
- 範圍:範圍依賴項在每次請求或生命週期範圍內建立一次,這意味著在單個請求或操作中,容器提供相同的實例。 這種一致性在網路應用程式中特別有用,因為範圍依賴有助於在網路請求中保持穩定的依賴。
- 瞬態:瞬態依賴每次從容器中請求時,都會實例化。 這意味著每當需要時,瞬態依賴項的新實例都會被生成。 通常,瞬態依賴項用於輕量級的、無狀態的服務或元件。
- 單例:單例依賴項僅被實例化一次,並在應用程式的整個生命週期內共享。這確保在應用程式的持續時間內,所有請求都使用相同的單例依賴項。 單例依賴通常用於需要在整個應用程式中普遍可存取的有狀態服務或元件。
安裝 Microsoft.Extensions.DependencyInjection 套件
要在 .NET Core 項目中開始使用依賴注入,您首先需要安裝Microsoft.Extensions.DependencyInjection 套件。 這可以通過在 Visual Studio 的 NuGet 套件管理器控制台中運行以下命令來完成:
Install-Package Microsoft.Extensions.DependencyInjection
截圖

範例:基本依賴注入
在這個範例中,讓我們建立一個使用範例應用程式(控制台應用程式),在其中我們將利用服務提供者來解析服務並將其注入到我們的程式中。
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
}
}
Imports Microsoft.Extensions.DependencyInjection
Imports System
' Define a service interface
Public Interface IMessageService
Sub SendMessage(ByVal message As String)
End Interface
' Implement the service interface
Public Class ConsoleMessageService
Implements IMessageService
Public Sub SendMessage(ByVal message As String) Implements IMessageService.SendMessage
Console.WriteLine(message) ' Output the message to the console
End Sub
End Class
程式碼片段建立了一個接口 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!");
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Create a service provider
Dim serviceProvider = (New ServiceCollection()).AddTransient(Of IMessageService, ConsoleMessageService)().BuildServiceProvider()
' Resolve the service
Dim messageService = serviceProvider.GetRequiredService(Of IMessageService)()
' Use the service to send a message
messageService.SendMessage("Hello, From Dependency Injection!")
End Sub
End Class
此程式碼設置了一個 serviceProvider 以管理服務。 它註冊 ConsoleMessageService 作為 IMessageService 的實現,使其可在需要時被注入。 Main 方法然後從 serviceProvider 檢索 IMessageService 的實例,並使用它向控制台發送消息。
輸出:程式列印字串消息"Hello, From Dependency Injection!"

IronPDF:C# PDF 程式庫
IronPDF 是一個功能強大的 C# 程式庫,簡化了 PDF 生成的複雜過程,提供了廣泛的 PDF 操作功能,包括從HTML 生成PDF,操作新增文字到PDF和編輯PDF與圖片,建立安全文件等等。

使用 IronPDF 與依賴注入
要將 IronPDF 程式庫整合到利用依賴注入功能和 Microsoft.Extensions.DependencyInjection 擴展方法的 .NET Core 應用程式中,您可以按以下步驟進行:
- 建立一個接口以定義您的 PDF 生成服務。
- 實現該接口。
- 利用擴展方法將服務註冊到依賴注入容器。
- 根據需要將服務注入到您的應用程式中。
定義接口
建立一個接口以定義您的 PDF 生成服務。
public interface IPdfService
{
void GeneratePdf(string baseUrl, string query, string filePath);
}
public interface IPdfService
{
void GeneratePdf(string baseUrl, string query, string filePath);
}
Public Interface IPdfService
Sub GeneratePdf(baseUrl As String, query As String, filePath As String)
End Interface
實現接口
using 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}");
}
}
Imports IronPdf
Imports System
Imports System.Web
' Implement the PDF generation interface
Public Class IronPdfService
Implements IPdfService
Public Sub GeneratePdf(ByVal baseUrl As String, ByVal query As String, ByVal filePath As String)
License.LicenseKey = "Your-License-Key" ' Set the IronPDF license key
Dim encodedQuery As String = HttpUtility.UrlEncode(query) ' Encode the query string
Dim fullUrl As String = $"{baseUrl}?query={encodedQuery}" ' Construct the full URL
Dim renderer = New ChromePdfRenderer() ' Create a PDF renderer
Dim 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}")
End Sub
End Class
註冊服務
在您的 Program.cs 類中配置依賴注入:
builder.Services.AddSingleton<IPdfService, IronPdfService>();
builder.Services.AddSingleton<IPdfService, IronPdfService>();
此設置通過實現 IPdfService 接口並使用 IronPdfService 來解析依賴項,建立一個用于 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();
}
}
Public Class MyController
Inherits Controller
Private ReadOnly _pdfService As IPdfService
Public Sub New(ByVal pdfService As IPdfService)
_pdfService = pdfService
End Sub
Public Function GeneratePdf() As IActionResult
Dim baseUrl As String = "https://ironpdf.com/"
Dim query As String = "Hello World from IronPDF !"
Dim filePath As String = "Demo.pdf"
' Use the injected PDF service to generate a PDF
_pdfService.GeneratePdf(baseUrl, query, filePath)
Return View()
End Function
End Class
此設置確保 IronPdfService 由 Microsoft Extensions Dependency Injection 容器建立和管理。 您可以通過為 IPdfService 接口提供替代實現來輕鬆替換預設的 PDF 生成服務,而不需要更改使用程式碼。
PDF 文件的截圖

結論
Microsoft.Extensions.DependencyInjection 是 .NET 6 中用於實現依賴注入的強大工具,促進鬆耦合並增強應用程式中的可測試性。 通過整合 IronPDF,一個功能豐富的 C# 程式庫,開發者可以輕鬆生成全面的 PDF 文件,並將所需的工作量降至最低。 IronPDF 授權 可用。
常見問題
Microsoft.Extensions.DependencyInjection 在 .NET 6 中扮演什麼角色?
Microsoft.Extensions.DependencyInjection 在 .NET 6 中用於實現依賴注入,這是一種設計模式,通過使用DI容器來管理服務的生命周期和依賴性,以建立鬆耦合的應用程式。
依賴注入如何增強應用程式的測試性?
依賴注入透過允許依賴項注入到類中來增強測試性,使其在測試期間更容易替換為模擬物件而不是實際實現。
在 .NET 應用程式中使用依賴注入的好處是什麼?
.NET 應用程式中使用依賴注入的好處包括提升程式碼可維護性、可擴展性以及能夠在運行時輕松管理和配置依賴項。
如何在 .NET Core 應用程式中實現依賴注入?
在 .NET Core 應用程式中,依賴注入是通過在應用程式啟動時配置 DI 容器中的服務,並根據需要將它們注入到構造函式或方法中來實現的。
如何在 .NET Core 應用程式中將 HTML 轉換為 PDF?
您可以使用 IronPDF 的方法在 .NET Core 應用程式中將 HTML 轉換為 PDF,例如 RenderHtmlAsPdf 用於 HTML 字串或 RenderHtmlFileAsPdf 用於 HTML 文件。
依賴注入中服務的不同生命周期是什麼,它們如何影響應用程式行為?
依賴注入中的服務生命周期包括範圍(Scoped)、瞬時(Transient)和單例(Singleton)。範圍服務每個請求建立一次,瞬時服務每次請求時建立,單例服務建立一次並在整個應用程式中共享。
如何在 .NET Core 項目中使用依賴注入整合 C# PDF 程式庫?
要在 .NET Core 項目中使用依賴注入整合 C# PDF 程式庫(如 IronPDF),您需要為PDF服務建立一個接口,實現它,將服務註冊到DI容器中,並根據需要將其注入到您的類中。
如何安裝 Microsoft.Extensions.DependencyInjection 套裝?
可以使用 Visual Studio 中的 NuGet 套裝管理器控制台安裝 Microsoft.Extensions.DependencyInjection 套裝,命令為:Install-Package Microsoft.Extensions.DependencyInjection。
如何使用依賴注入與 IronPDF 生成PDF?
可以通過設置 PDF 服務接口,使用 IronPDF 方法實現它,並在 DI 容器中註冊來使用 IronPDF 與依賴注入。然後可以注入並使用該服務從 URL 或 HTML 內容生成 PDF。
您可以在不更改消費程式碼的情況下在 DI 設置中替換 C# PDF 程式庫嗎?
是的,您可以通過對用於 PDF 服務的接口實現替代方案來在 DI 設置中替換 C# PDF 程式庫,這樣您就可以在不更改消費程式碼的情況下切換程式庫。




