Microsoft.Extensions.DependencyInjection .NET 9(在 PDF 中的应用)
Microsoft.Extensions.DependencyInjection 是由 Microsoft .NET 提供的一个强大的库,用于促进依赖注入 (DI),这是一种软件设计模式,促进松耦合并增强应用程序的可测试性。 DI 通常使用内置的 .NET Core DI 容器或类似 Autofac 和 Unity 的库来实现。 DI 涉及将依赖项(类所需要的对象)注入到一个类中,而不是让类自己创建其依赖项。 这通常通过构造函数、方法或属性注入来完成。

依赖注入容器
-
服务注册:依赖项在 DI 容器中注册,通常位于应用程序的组合根。 这些注册指定了容器应如何创建和管理依赖项。
-
依赖解析:当组件请求依赖项时,DI 容器通过创建使用扩展方法的注册类型的实例来解析依赖项。
依赖注入的类型
- 构造函数注入: 注册的服务通过构造函数提供给类,这是最常见和推荐的 DI 形式。
- 方法注入:服务被解析并作为参数传递给方法。
- 属性注入:单例服务或具有作用域生命周期的服务可以分配给类属性。 然而,这种方法不太常见,并且通常被认为不如构造函数注入,因为它可能引入隐藏的依赖项。
理解依赖注入(DI)中的生命周期:作用域、瞬态和单例
- 作用域: 作用域依赖项每个请求或生命周期范围创建一次,这意味着容器在单个请求或操作中提供相同的实例。 这种一致性在 Web 应用程序中特别有用,因为作用域依赖项有助于在整个 Web 请求中保持稳定的依赖项。
- 瞬态: 瞬态依赖项每次从容器请求时都会实例化。 这意味着每次需要瞬态依赖项时,都会生成一个新实例。 通常,瞬态依赖项用于轻量级、无状态的服务或组件。
- 单例: 单例依赖项只实例化一次,并在应用程序的整个生命周期中共享。这确保了在应用程序的整个期间,为所有请求使用同一个单例依赖项实例。 单例依赖项通常用于状态服务或需要在整个应用程序中普遍访问的组件。
安装 Microsoft.Extensions.DependencyInjection 包
要在 .NET Core 项目中开始使用依赖注入,首先需要安装 Microsoft.Extensions.DependencyInjection 包。 这可以通过 Visual Studio 中的 NuGet 包管理器控制台使用以下命令完成:
截图

示例:基本依赖注入
在这个示例中,让我们创建一个示例应用程序(控制台应用程序),其中我们将利用服务提供者来解析服务并将其注入到我们的程序中。
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 ClassImports 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用于发送消息,如同消息发送的规范。 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 ClassFriend 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、操作添加 文本到 PDFs 和 使用图像编辑 PDFs、创建安全文档等等。

使用依赖注入与 IronPDF
要将 IronPDF 库集成到一个 leveraing 依赖注入功能和扩展方法与 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 InterfacePublic 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 ClassImports 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>();netnet此设置通过使用 IronPDFService 实现 IPdfService 接口来解析依赖项,建立用于 PDF 生成的单例服务类型。 然后在整个应用程序中引用它,确保生成 PDFs 的一致功能。
用法
将 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(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 ClassPublic Class MyController
Inherits Controller
Private ReadOnly _pdfService As IPdfService
Public Sub New(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 的许可 可用。
Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。