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

依賴注入容器
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
螢幕快照
。
範例:基本的依賴注入
在本範例中,讓我們建立一個範例應用程式 (主控台應用程式),其中我們將運用服務提供者來解析服務,並將它們注入我們的程式中。
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 與依賴注入。
若要利用 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);
}
Public Interface IPdfService
Sub GeneratePdf(baseUrl As String, query As String, filePath As String)
End Interface
實作介面
使用 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>();
此設定透過使用 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();
}
}
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 中用於實現依賴注入(Dependency Injection),這是一種設計模式,透過 DI 容器管理服務的生命週期和依賴關係來幫助創建鬆耦合的應用程式。
依賴注入如何增強應用程式的可測試性?
依賴注入透過允許將依賴注入到一個類中來增強可測試性,這使得在測試期間更容易替換模擬對象而非真實實現。
在 .NET 應用程式中使用依賴注入的好處是什麼?
.NET 應用程式中使用依賴注入的好處包括改進代碼的可維護性、可擴展性以及能夠在運行時輕鬆管理和配置依賴。
如何在 .NET Core 應用程式中實施依賴注入?
在 .NET Core 應用程式中,依賴注入是通過在應用程式啟動期間在 DI 容器中配置服務,並根據需要將它們注入到構造函數或方法中來實施的。
如何在 .NET Core 應用程式中將 HTML 轉換為 PDF?
您可以在 .NET Core 應用程式中使用 IronPDF 方法來將 HTML 轉換為 PDF,例如用於 HTML 字串的 RenderHtmlAsPdf 或用於 HTML 文件的 RenderHtmlFileAsPdf。
依賴注入中服務的不同生命週期是什麼,它們如何影響應用程式行為?
依賴注入中的服務生命週期包括 Scoped、Transient 和 Singleton。Scoped 服務每個請求創建一次,Transient 服務每次請求都創建,Singleton 服務僅創建一次並在整個應用中共享。
在 .NET 6 中,Dependency Injection 用於實現依賴注入(DI),這種設計模式通過 DI 容器管理服務的生命週期和依賴,幫助創建鬆耦合的應用程式。
要在 .NET Core 項目中使用依賴注入集成 C# PDF 庫(如 IronPDF),您需要為 PDF 服務創建一個接口,實施它,將該服務註冊到 DI 容器中,並根據需要將其注入到類中。
安裝 Microsoft.Extensions.DependencyInjection 套件的過程是什麼?
可以使用 Visual Studio 的 NuGet 包管理控制台安裝 Microsoft.Extensions.DependencyInjection 套件,命令為:Install-Package Microsoft.Extensions.DependencyInjection。
如何使用 IronPDF 和依賴注入來生成 PDF?
可以使用 IronPDF 配合依賴注入來生成 PDF,方法是設置一個 PDF 服務接口,用 IronPDF 方法實施它,並將其註冊到 DI 容器。然後可以注入這個服務並使用它從 URL 或 HTML 內容生成 PDF。
可以在不更改消費代碼的情況下在 DI 設置中替換 C# PDF 庫嗎?
是的,您可以通過實施 PDF 服務接口的替代版本來在 DI 設置中替換 C# PDF 庫,這樣可以在不更改消費代碼的情況下切換庫。



