Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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.
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.
// writing code
var builder = WebApplication.CreateBuilder(args);
// Add MediatR
builder.Services.AddMediatR(typeof(Program).Assembly);
var app = builder.Build();
// writing code
var builder = WebApplication.CreateBuilder(args);
// Add MediatR
builder.Services.AddMediatR(typeof(Program).Assembly);
var app = builder.Build();
' writing code
Dim builder = WebApplication.CreateBuilder(args)
' Add MediatR
builder.Services.AddMediatR(GetType(Program).Assembly)
Dim app = builder.Build()
In the program class, var builder = WebApplication.CreateBuilder(args); initializes the web application, setting the stage for MediatR integration.
MediatR requests are simple classes, such as a public class email handler, that represent the data needed to perform a specific operation. Here's an example of a request public 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 public async Task Handle method is the core 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 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 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 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
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.
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.
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.
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)
{
License.LicenseKey = "License-Key";
// Initialize the HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Example HTML content - replace this with your actual HTML content
// Here, "htmlContent" should include your MediatR information in HTML format
string htmlTemplate = $@"
<html>
<head>
<title>Media Information</title>
</head>
<body>
<h1>Media Details</h1>
<!-- Insert your media information here -->
{htmlContent}
</body>
</html>";
// Convert HTML string to PDF
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)
{
License.LicenseKey = "License-Key";
// Initialize the HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Example HTML content - replace this with your actual HTML content
// Here, "htmlContent" should include your MediatR information in HTML format
string htmlTemplate = $@"
<html>
<head>
<title>Media Information</title>
</head>
<body>
<h1>Media Details</h1>
<!-- Insert your media information here -->
{htmlContent}
</body>
</html>";
// Convert HTML string to PDF
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)
License.LicenseKey = "License-Key"
' Initialize the HtmlToPdf renderer
Dim renderer = New ChromePdfRenderer()
' Example HTML content - replace this with your actual HTML content
' Here, "htmlContent" should include your MediatR information in HTML format
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 HTML string to PDF
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.
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.
9 .NET API products for your office documents