Skip to footer content
.NET HELP

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();
' Initialize a new web application
Dim builder = WebApplication.CreateBuilder(args)

' Add MediatR to the service container
builder.Services.AddMediatR(GetType(Program).Assembly)

' Build the web application
Dim 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; }
}
Public Class CreateUserCommand
	Implements IRequest(Of Integer)

	Public Property Name() As String
	Public Property Email() As String
	Public Property Id() As Integer
End Class
$vbLabelText   $csharpLabel

In this example, the CreateUserCommand class implements the IRequestinterface, 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
    }
}
Public Class CreateUserHandler
	Implements IRequestHandler(Of CreateUserCommand, Integer)

	Public Async Function Handle(ByVal command As CreateUserCommand, ByVal token As CancellationToken) As Task(Of Integer)
		' 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
	End Function
End Class
$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);
    }
}
<ApiController>
<Route("[controller]")>
Public Class UsersController
	Inherits ControllerBase

	Private ReadOnly _mediator As IMediator

	Public Sub New(ByVal mediator As IMediator)
		_mediator = mediator
	End Sub

	<HttpPost>
	Public Async Function Create(ByVal command As CreateUserCommand) As Task(Of ActionResult(Of Integer))
		Dim userId = Await _mediator.Send(command)
		Return CreatedAtRoute("GetUser", New With {Key .id = userId}, command)
	End Function
End Class
$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");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

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

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

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$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>
                <!-- Insert your media information here -->
                {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>
                <!-- Insert your media information here -->
                {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.");
    }
}
Imports IronPdf

Public Class PdfGenerator
	Public Sub CreatePdfWithMediaInfo(ByVal htmlContent As String)
		' Insert your License Key here if required
		License.LicenseKey = "License-Key"

		' Initialize the HtmlToPdf renderer
		Dim renderer = New ChromePdfRenderer()

		' Create an HTML template with media information
		Dim htmlTemplate As String = $"
            <html>
            <head>
                <title>Media Information</title>
            </head>
            <body>
                <h1>Media Details</h1>
                <!-- Insert your media information here -->
                {htmlContent}
            </body>
            </html>"

		' Convert the HTML string to a PDF document
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlTemplate)
		pdfDocument.SaveAs("MediaInformation.pdf")
	End Sub
End Class

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Example HTML content with MediatR information
		Dim htmlContent As String = "
            <div>
                <h2>MediatR Information</h2>
                <p>MediatR is a media tracking system...</p>
            </div>"

		' Create an instance of PdfGenerator
		Dim pdfGenerator As New PdfGenerator()

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

		Console.WriteLine("PDF generated successfully.")
	End Sub
End Class
$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 $749, offering a robust solution for .NET developers looking to extend their application's functionalities.

Frequently Asked Questions

What is a popular C# library for implementing the mediator pattern?

MediatR is a .NET library implementing the mediator pattern, allowing objects to communicate through a mediator to reduce direct dependencies and promote loose coupling.

How does the mediator pattern benefit application design?

The mediator pattern reduces direct dependencies between objects, promoting loose coupling and making applications easier to maintain and scale.

How can I install a mediator pattern library in an ASP.NET Core project?

You can install MediatR in an ASP.NET Core project using the Package Manager Console with the command: Install-Package MediatR.

What are requests and handlers in a mediator pattern library?

MediatR requests are classes encapsulating operation details, while handlers process these requests with the necessary business logic, supporting the CQRS pattern.

How do I integrate a mediator pattern library into my web application?

Integrate MediatR by adding it to the ASP.NET Core dependency injection container, typically in the Program.cs or Startup.cs file, and use it within your application's workflow.

What are notifications and behaviors in a mediator pattern library?

Notifications allow multiple handlers to respond to messages, while behaviors act like middleware for requests, handling cross-cutting concerns such as logging or validation.

What library can be used for PDF functionalities in .NET applications?

IronPDF is a C# library for creating, editing, and managing PDF files in .NET applications, supporting features like HTML to PDF conversion, editing, and securing PDFs.

How can I convert HTML to a PDF in .NET applications?

Using IronPDF, you can convert HTML to PDF by initializing a ChromePdfRenderer and using methods like RenderHtmlAsPdf or RenderUrlAsPdf with the HTML content or URL.

What are some advanced PDF features available in .NET libraries?

IronPDF offers advanced features such as merging, splitting, editing PDFs, and securing them with passwords and permissions, ideal for generating reports, invoices, and documentation.

What is the purpose of using a mediator pattern library in .NET projects?

MediatR helps in organizing code by decoupling communication between objects, supporting clean architecture principles, and facilitating the implementation of design patterns like CQRS.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.