Microsoft.Extensions .DependencyInjection .NET 9 (Praca z PDF)
Microsoft.Extensions.DependencyInjection is a powerful library provided by Microsoft .NET to facilitate Dependency Injection (DI), a software design pattern that promotes loose coupling and enhances testability in applications. DI is often implemented using .NET Core built-in DI container or libraries like Autofac and Unity. DI involves injecting dependencies (objects a class needs) into a class rather than the class creating its dependencies. This is typically done through a constructor, method, or property injection.

Dependency Injection Container
-
Service Registration: Dependencies are registered in a DI container, typically at the application's composition root. These registrations specify how the container should create and manage the dependencies.
- Dependency Resolution: When a component requests a dependency, the DI container resolves the dependency by creating an instance of a registered type that uses an extension method.
Types of Dependency Injection
- Constructor Injection: Registered services are provided to a class through its constructor, which is the most common and recommended form of DI.
- Method Injection: Services are resolved and passed as parameters to a method.
- Property Injection: Singleton services or services with a scoped lifetime can be assigned to class properties. However, this approach is less common and often considered inferior to constructor injection because it can introduce hidden dependencies.
Understanding Lifetimes in Dependency Injection (DI): Scoped, Transient, and Singleton
- Scoped: Scoped dependencies are created once per request or lifetime scope, meaning the container provides the same instance within a single request or operation. This consistency is particularly useful in web applications, where scoped dependencies help maintain a stable dependency throughout a web request.
- Transient: Transient dependencies are instantiated each time they are requested from the container. Oznacza to, że nowa instancja zależności przejściowej jest generowana zawsze wtedy, gdy jest potrzebna. Zazwyczaj zależności przejściowe są używane w przypadku lekkich, bezstanowych usług lub komponentów.
- Singleton: Zależności typu singleton są instancjonowane tylko raz i współdzielone przez cały okres działania aplikacji. Gwarantuje to, że ta sama instancja zależności typu singleton jest używana dla wszystkich żądań przez cały czas działania aplikacji. Zależności typu singleton są zazwyczaj stosowane w przypadku usług lub komponentów stanowych, które muszą być powszechnie dostępne w całej aplikacji.
Instalacja pakietu Microsoft.Extensions.DependencyInjection
Aby rozpocząć korzystanie z wstrzykiwania zależności w projekcie .NET Core, należy najpierw zainstalować pakiet Microsoft.Extensions.DependencyInjection. Można to zrobić za pomocą konsoli menedżera pakietów NuGet w Visual Studio, używając następującego polecenia:
Install-Package Microsoft.Extensions.DependencyInjection
Zrzut ekranu

Przykład: Podstawowe wstrzykiwanie zależności
W tym przykładzie stworzymy przykładową aplikację (aplikację konsolową), w której wykorzystamy dostawcę usług do rozpoznawania usług i wstrzykiwania ich do naszego programu.
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
The code snippet creates an interface IMessageService for sending messages, like a contract for how messages should be sent. The ConsoleMessageService class implements this interface by using Console.WriteLine to send messages. Takie rozdzielenie pozwala na zmianę koncepcji wysyłania wiadomości niezależnie od sposobu ich wysyłania, dzięki czemu system jest elastyczny i łatwy w zarządzaniu.
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
Ten kod konfiguruje obiekt serviceProvider do zarządzania usługami. Rejestruje ConsoleMessageService jako implementację dla IMessageService, dzięki czemu można go wstrzyknąć tam, gdzie jest to wymagane. The Main method then retrieves an instance of IMessageService from the serviceProvider and uses it to send a message to the console.
Wynik: Program wyświetla komunikat "Hello, From Dependency Injection!".

IronPDF: biblioteka PDF dla języka C
IronPDF to potężna biblioteka dla języka C#, która upraszcza złożony proces generowania plików PDF, oferując szeroki zakres funkcji do manipulacji plikami PDF, w tym możliwość generowania plików PDF z HTML, dodawania tekstu do plików PDF i edycji plików PDF z obrazami, tworzenia bezpiecznych dokumentów i wiele więcej.

Korzystanie z IronPDF z wstrzykiwaniem zależności
Aby zintegrować bibliotekę IronPDF z aplikacją .NET Core, wykorzystując funkcje wstrzykiwania zależności i metody rozszerzeń za pomocą Microsoft.Extensions.DependencyInjection, można postępować w następujący sposób:
- Utwórz interfejs do zdefiniowania usługi generowania plików PDF.
- Zaimplementuj interfejs.
- Wykorzystaj metody rozszerzeń, aby zarejestrować usługę w kontenerze wstrzykiwania zależności.
- Włącz usługę do swojej aplikacji zgodnie z wymaganiami.
Zdefiniuj interfejs
Utwórz interfejs do definiowania usługi generowania plików 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
Zaimplementuj interfejs
Zaimplementuj interfejs przy użyciu IronPDF do tworzenia pliku 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
Zarejestruj usługę
In your Program.cs class, configure dependency injection:
builder.Services.AddSingleton<IPdfService, IronPdfService>();
builder.Services.AddSingleton<IPdfService, IronPdfService>();
Ta konfiguracja rozwiązuje zależności poprzez implementację interfejsu IPdfService za pomocą IronPdfService, tworząc singletonowy typ usługi do generowania plików PDF. Następnie jest on wykorzystywany w całej aplikacji, zapewniając spójną funkcjonalność generowania plików PDF.
Zastosowanie
Wstrzyknij IPdfService do swojego kontrolera lub usługi i korzystaj z niego:
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
Ta konfiguracja gwarantuje, że IronPdfService jest tworzony i zarządzany przez kontener wstrzykiwania zależności Microsoft Extensions. Możesz bez trudu zastąpić domyślną usługę generowania plików PDF, oferując alternatywną implementację interfejsu IPdfService, a wszystko to bez zmiany kodu użytkownika.
Zrzut ekranu pliku PDF

Wnioski
Microsoft.Extensions.DependencyInjection to potężne narzędzie w .NET 6 służące do wdrażania wstrzykiwania zależności, które sprzyja luźnemu sprzężeniu i zwiększa testowalność aplikacji. Dzięki integracji z IronPDF, bogatą w funkcje biblioteką C#, programiści mogą z łatwością generować kompleksowe dokumenty PDF przy minimalnym wysiłku. Dostępne są licencje na IronPDF.
Często Zadawane Pytania
Jaka jest rola Microsoft.Extensions.DependencyInjection w .NET 6?
Microsoft.Extensions.DependencyInjection w .NET 6 jest używany do wdrożenia Dependency Injection, wzorca projektowego, który pomaga w tworzeniu luźno powiązanych aplikacji poprzez zarządzanie żywotnościami usług i zależnościami za pomocą kontenera DI.
W jaki sposób Dependency Injection może zwiększyć testowalność aplikacji?
Dependency Injection zwiększa testowalność, umożliwiając wtryskiwanie zależności do klasy, co ułatwia zamianę obiektów mock podczas testowania zamiast realnych implementacji.
Jakie są korzyści z używania Dependency Injection w aplikacjach .NET?
Korzyści z używania Dependency Injection w aplikacjach .NET obejmują poprawę zrównoważenia kodu, skalowalność oraz możliwość łatwego zarządzania i konfigurowania zależności podczas runtime.
Jak wdrożyć Dependency Injection w aplikacji .NET Core?
W aplikacji .NET Core Dependency Injection jest wdrażany poprzez konfigurowanie usług w kontenerze DI podczas uruchamiania aplikacji i wstrzykiwanie ich do konstruktorów lub metod, w zależności od potrzeb.
Jak przekonwertować HTML na PDF w aplikacji .NET Core?
Możesz przekonwertować HTML na PDF w aplikacji .NET Core, używając metody IronPDF, takiej jak RenderHtmlAsPdf dla ciągów HTML lub RenderHtmlFileAsPdf dla plików HTML.
Jakie są różne żywotności usług w Dependency Injection i jak wpływają one na zachowanie aplikacji?
Żywotności usług w Dependency Injection to Scoped, Transient i Singleton. Usługi scoped są tworzone raz na żądanie, usługi transient są tworzone za każdym razem, gdy są żądane, a singletony są tworzone raz i współdzielone w całej aplikacji.
Jak zintegrować bibliotekę PDF C# w projekcie .NET Core przy użyciu Dependency Injection?
Aby zintegrować bibliotekę PDF C#, taką jak IronPDF, w projekcie .NET Core przy użyciu Dependency Injection, musisz stworzyć interfejs dla usług PDF, zaimplementować go, zarejestrować usługę w kontenerze DI i wstrzyknąć ją do swoich klas w miarę potrzeby.
Jaki jest proces instalacji pakietu Microsoft.Extensions.DependencyInjection?
Pakiet Microsoft.Extensions.DependencyInjection można zainstalować za pomocą konsoli Menedżera pakietów NuGet w Visual Studio za pomocą komendy: Install-Package Microsoft.Extensions.DependencyInjection.
Jak użyć IronPDF z Dependency Injection do generowania PDF-ów?
IronPDF można używać z Dependency Injection poprzez skonfigurowanie interfejsu usługi PDF, zaimplementowanie go za pomocą metod IronPDF i zarejestrowanie w kontenerze DI. Usługa może być następnie wstrzyknięta i używana do generowania PDF-ów z URL lub treści HTML.
Czy możesz zastąpić bibliotekę PDF C# w konfiguracji DI bez zmiany kodu konsumującego?
Tak, można zastąpić bibliotekę PDF C# w konfiguracji DI, implementując alternatywę dla interfejsu używanego do usług PDF, co pozwala na zamianę bibliotek bez zmiany kodu konsumującego.




