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
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
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()
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
In this example, the CreateUserCommand class implements the IRequest
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
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
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
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
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
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.
Conclusion
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
How can MediatR be integrated into ASP.NET Core projects?
To integrate MediatR into an ASP.NET Core project, add it to the dependency injection container in your Program.cs or Startup.cs file. You can install it using the Package Manager Console with the command: Install-Package MediatR
.
What role do requests and handlers play in MediatR?
In MediatR, requests encapsulate the details of an operation, and handlers process these requests by executing the necessary business logic. This supports the Command Query Responsibility Segregation (CQRS) pattern, enhancing the maintainability of applications.
How do notifications and behaviors enhance MediatR?
Notifications in MediatR allow multiple handlers to react to a single message, promoting an event-driven approach. Behaviors function as middleware to handle cross-cutting concerns like logging, validation, and exception handling.
What are the benefits of using the mediator pattern in .NET applications?
The mediator pattern, implemented by MediatR, reduces direct dependencies among components, promoting loose coupling. This enhances the maintainability and scalability of .NET applications by following clean architecture principles.
How can HTML be converted to PDF in .NET applications?
IronPDF allows the conversion of HTML to PDF in .NET applications. You can use the RenderHtmlAsPdf
method to convert HTML strings or RenderUrlAsPdf
for URLs, ensuring the layout is preserved in the resulting PDF.
What advanced features does IronPDF offer for PDF management?
IronPDF provides advanced PDF management features such as merging, splitting, editing PDFs, and securing them with passwords and permissions. These capabilities are ideal for tasks such as generating reports, invoices, and other documentation.
How does MediatR support the CQRS pattern?
MediatR supports the CQRS pattern by separating the logic that handles command requests from queries. This separation allows for more scalable and maintainable code, as each operation type can be independently optimized and managed.
What are the advantages of using IronPDF in .NET projects?
IronPDF provides an easy-to-use API for creating, editing, and managing PDF files in .NET projects. Its ability to convert HTML to PDF while preserving the layout makes it a powerful tool for generating reports and documents.