푸터 콘텐츠로 바로가기
.NET 도움말

Mediatr C# (How It Works For Developers)

MediatR is a popular .NET library that implements the mediator pattern, enabling objects to communicate with each other through a mediator, rather than directly. This approach is particularly useful in applications where maintaining a low level of coupling between components is desirable. In this article, we will take a detailed look at MediatR in the context of C# development, providing practical examples and guidance on how to integrate it into your web application projects. We'll also explore the IronPDF library for PDF functionalities in .NET applications for the integration of PDF functionalities in ASP.NET Core projects.

Introduction to the Mediator Pattern and MediatR

Mediatr C# (How It Works For Developers): Figure 1 - MediatR and Mediator Pattern

The mediator pattern is a software design pattern that facilitates the interaction between objects in a manner that reduces direct dependencies between them, promoting loose coupling. MediatR provides an unambitious mediator implementation, focusing on simplicity and efficiency in facilitating object communication.

At the heart of the MediatR library is the concept of requests and multiple handlers. At the request point, an object encapsulates the operation or action details, awaiting processing by the MediatR mechanism. Each request is handled by a corresponding handler or handle method, which contains the business logic to execute the request. This structure is particularly useful for implementing the Command Query Responsibility Segregation (CQRS) pattern, where the separation of read and write operations can lead to more maintainable and scalable software architectures.

Installing MediatR in a .NET Core Project using Package Manager Console

To start using MediatR in an ASP.NET Core project, you first need to install the MediatR package. This can be done through the Package Manager Console in Visual Studio with the following command:

Install-Package MediatR

Mediatr C# (How It Works For Developers): Figure 2 - Install MediatR

After installing the package, it's necessary to add MediatR to the ASP.NET Core dependency injection container. This is typically done in the Program.cs or Startup.cs file of your web application project, depending on the version of ASP.NET Core you're using. Here's how you can do it in a program with a minimal API presentation layer.

// Initialize a new web application
var builder = WebApplication.CreateBuilder(args);

// Add MediatR to the service container
builder.Services.AddMediatR(typeof(Program).Assembly);

// Build the web application
var app = builder.Build();
// Initialize a new web application
var builder = WebApplication.CreateBuilder(args);

// Add MediatR to the service container
builder.Services.AddMediatR(typeof(Program).Assembly);

// Build the web application
var app = builder.Build();
$vbLabelText   $csharpLabel

In the program class, var builder = WebApplication.CreateBuilder(args); initializes the web application, setting the stage for MediatR integration.

Creating Your First MediatR Request and Handler

MediatR requests are simple classes that represent the data needed to perform a specific operation. Here's an example of a request class that represents a command to create a new user.

public class CreateUserCommand : IRequest<int>
{
    public string Name { get; set; }
    public string Email { get; set; }
    public int Id { get; set; }
}
public class CreateUserCommand : IRequest<int>
{
    public string Name { get; set; }
    public string Email { get; set; }
    public int Id { get; set; }
}
$vbLabelText   $csharpLabel

In this example, the CreateUserCommand class implements the IRequest interface, indicating that this request expects an integer response, which could represent the ID of the created user.

Next, you need to create a handler for this request. Within each handler, the Handle method is where the request's logic is executed:

public class CreateUserHandler : IRequestHandler<CreateUserCommand, int>
{
    public async Task<int> Handle(CreateUserCommand command, CancellationToken token)
    {
        // Implement logic to create a user here
        // For this example, let's pretend we create a user and return the ID
        return await Task.FromResult(1); // Assume the user's ID is 1
    }
}
public class CreateUserHandler : IRequestHandler<CreateUserCommand, int>
{
    public async Task<int> Handle(CreateUserCommand command, CancellationToken token)
    {
        // Implement logic to create a user here
        // For this example, let's pretend we create a user and return the ID
        return await Task.FromResult(1); // Assume the user's ID is 1
    }
}
$vbLabelText   $csharpLabel

Using MediatR in Your Application

By following the same process used in setting up MediatR, you integrate it within your application's workflow. This is typically done through a controller or endpoint in an ASP.NET Core application. Here's an example using an API controller:

[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    private readonly IMediator _mediator;

    public UsersController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<ActionResult<int>> Create(CreateUserCommand command)
    {
        var userId = await _mediator.Send(command);
        return CreatedAtRoute("GetUser", new { id = userId }, command);
    }
}
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    private readonly IMediator _mediator;

    public UsersController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<ActionResult<int>> Create(CreateUserCommand command)
    {
        var userId = await _mediator.Send(command);
        return CreatedAtRoute("GetUser", new { id = userId }, command);
    }
}
$vbLabelText   $csharpLabel

In this controller, the Create action method sends the CreateUserCommand to MediatR by calling _mediator.Send(command). MediatR then finds the appropriate handler for this command and executes it. The result is returned and used to generate a response in the same process.

Beyond Basic Requests: Notifications and Behaviors

MediatR also supports notifications and behaviors. Notifications are messages that multiple handlers can subscribe to and handle, allowing for a more event-driven approach within your application. Behaviors, on the other hand, are akin to middleware for your MediatR requests, allowing you to implement cross-cutting concerns like logging, validation, or transaction management.

Introduction of IronPDF Library

Mediatr C# (How It Works For Developers): Figure 3 - IronPDF

IronPDF is a C# library designed for .NET developers who need a straightforward way to create, edit, and work with PDF files in their applications without any write concerns. Developers can generate PDFs without engaging with complex APIs by simply converting web pages or HTML code directly into PDF format. IronPDF is not just limited to creating PDFs; it also offers features for editing PDFs, such as adding text, images, and pages, or even filling out and editing forms within PDF documents. Developers can comprehensively work with PDFs, including tasks like merging, splitting, and securing PDF files with passwords and permissions.

IronPDF specializes in converting HTML to PDF preserving original layouts and styles with precision. This makes it ideal for generating PDFs from web-based content like reports, invoices, and documentation. It supports conversion from HTML files, URLs, and even raw HTML strings into PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

Code Example

In this example, let's assume MediatR request refers to some form of media content or metadata that we want to include in our PDF. Since MediatR isn't directly related to IronPDF's functionality, we'll approach this by creating a PDF document from HTML content that includes media information or references as a great starting point.

using IronPdf;

public class PdfGenerator
{
    public void CreatePdfWithMediaInfo(string htmlContent)
    {
        // Insert your License Key here if required
        License.LicenseKey = "License-Key";

        // Initialize the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();

        // Create an HTML template with media information
        string htmlTemplate = $@"
            <html>
            <head>
                <title>Media Information</title>
            </head>
            <body>
                <h1>Media Details</h1>

                {htmlContent}
            </body>
            </html>";

        // Convert the HTML string to a PDF document
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlTemplate);
        pdfDocument.SaveAs("MediaInformation.pdf");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Example HTML content with MediatR information
        string htmlContent = @"
            <div>
                <h2>MediatR Information</h2>
                <p>MediatR is a media tracking system...</p>
            </div>";

        // Create an instance of PdfGenerator
        PdfGenerator pdfGenerator = new PdfGenerator();

        // Call the CreatePdfWithMediaInfo method to generate the PDF
        pdfGenerator.CreatePdfWithMediaInfo(htmlContent);

        Console.WriteLine("PDF generated successfully.");
    }
}
using IronPdf;

public class PdfGenerator
{
    public void CreatePdfWithMediaInfo(string htmlContent)
    {
        // Insert your License Key here if required
        License.LicenseKey = "License-Key";

        // Initialize the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();

        // Create an HTML template with media information
        string htmlTemplate = $@"
            <html>
            <head>
                <title>Media Information</title>
            </head>
            <body>
                <h1>Media Details</h1>

                {htmlContent}
            </body>
            </html>";

        // Convert the HTML string to a PDF document
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlTemplate);
        pdfDocument.SaveAs("MediaInformation.pdf");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Example HTML content with MediatR information
        string htmlContent = @"
            <div>
                <h2>MediatR Information</h2>
                <p>MediatR is a media tracking system...</p>
            </div>";

        // Create an instance of PdfGenerator
        PdfGenerator pdfGenerator = new PdfGenerator();

        // Call the CreatePdfWithMediaInfo method to generate the PDF
        pdfGenerator.CreatePdfWithMediaInfo(htmlContent);

        Console.WriteLine("PDF generated successfully.");
    }
}
$vbLabelText   $csharpLabel

In this code snippet, htmlContent is a variable that should contain your media information in HTML format. This could include text, images, links to videos, or any other HTML-compatible content. IronPDF will convert this HTML content into a PDF document, preserving the layout and formatting specified in the HTML.

Mediatr C# (How It Works For Developers): Figure 4 - PDF Output

Conclusion

Mediatr C# (How It Works For Developers): Figure 5 - Licensing

By following the steps outlined in this article, you should now have a solid foundation for incorporating MediatR into your projects, starting from basic command and query handling to leveraging more advanced features like notifications and behaviors. As your application grows and evolves, MediatR offers tools and patterns that can help keep your codebase clean, maintainable, and scalable.

As we conclude, it's worth noting that exploring and integrating different libraries and tools, such as IronPDF, can further enhance your .NET projects. IronPDF offers a free trial of advanced PDF features. For projects requiring advanced PDF features, IronPDF's licensing starts from $799, offering a robust solution for .NET developers looking to extend their application's functionalities.

자주 묻는 질문

MediatR을 ASP.NET Core 프로젝트에 어떻게 통합할 수 있나요?

ASP.NET Core 프로젝트에 MediatR을 통합하려면 Program.cs 또는 Startup.cs 파일의 종속성 주입 컨테이너에 추가하세요. 패키지 관리자 콘솔에서 다음 명령을 사용하여 설치할 수 있습니다: Install-Package MediatR.

요청과 핸들러는 MediatR에서 어떤 역할을 하나요?

MediatR에서 요청은 작업의 세부 사항을 캡슐화하고 핸들러는 필요한 비즈니스 로직을 실행하여 이러한 요청을 처리합니다. 이는 명령 쿼리 책임 분리(CQRS) 패턴을 지원하여 애플리케이션의 유지보수성을 향상시킵니다.

알림과 동작은 MediatR을 어떻게 개선하나요?

MediatR의 알림을 사용하면 여러 핸들러가 단일 메시지에 반응하여 이벤트 중심 접근 방식을 촉진할 수 있습니다. 동작은 로깅, 유효성 검사 및 예외 처리와 같은 교차적인 문제를 처리하는 미들웨어로 작동합니다.

.NET 애플리케이션에서 중개자 패턴을 사용하면 어떤 이점이 있나요?

MediatR이 구현하는 매개자 패턴은 구성 요소 간의 직접적인 종속성을 줄여 느슨한 결합을 촉진합니다. 이는 깔끔한 아키텍처 원칙을 준수하여 .NET 애플리케이션의 유지 관리 및 확장성을 향상시킵니다.

.NET 애플리케이션에서 HTML을 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF를 사용하면 .NET 애플리케이션에서 HTML을 PDF로 변환할 수 있습니다. HTML 문자열의 경우 RenderHtmlAsPdf 메서드를 사용하여 변환하거나 URL의 경우 RenderUrlAsPdf를 사용하여 결과 PDF에서 레이아웃이 유지되도록 할 수 있습니다.

IronPDF는 PDF 관리를 위해 어떤 고급 기능을 제공하나요?

IronPDF는 PDF 병합, 분할, 편집, 비밀번호 및 권한으로 보안 설정과 같은 고급 PDF 관리 기능을 제공합니다. 이러한 기능은 보고서, 송장 및 기타 문서 생성과 같은 작업에 이상적입니다.

MediatR은 CQRS 패턴을 어떻게 지원하나요?

MediatR은 명령 요청을 처리하는 로직과 쿼리를 분리하여 CQRS 패턴을 지원합니다. 이러한 분리를 통해 각 작업 유형을 독립적으로 최적화하고 관리할 수 있으므로 보다 확장 가능하고 유지 관리가 쉬운 코드를 만들 수 있습니다.

.NET 프로젝트에서 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 .NET 프로젝트에서 PDF 파일을 생성, 편집 및 관리하기 위한 사용하기 쉬운 API를 제공합니다. 레이아웃을 유지하면서 HTML을 PDF로 변환하는 기능은 보고서 및 문서 생성을 위한 강력한 도구입니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.