In a previous post, we explain how to build a web API with CQRS and MediatR.How to Build a Clean WebAPI Net 6.
Why migrate to MediatR V12
MediatR v12 is the latest version of MediatR, and it comes with several new features and improvements. If you're currently using an older version of MediatR and want to upgrade to v12, here's how to do it:
Step 1: Update the Nuget packages.
We first need to remove the current MediatR Nugets and add the latest version since the newest version is all-in, assuming we are using MediatR with dependency injection.
*MediatR
*MediatR.Extensions.Microsoft.DependencyInjection
we can use this command from PowerShell or terminal using dotnet cli to remove the current nugets:
dotnet remove package MediatR
dotnet remove package MediatR.Extensions.Microsoft.DependencyInjection
Then the current nugets are removed, and the next step is to add the latest version.
dotnet add package MediatR --version 12.0.0
Step 2 : Update the mediator registration
The way of registration has changed; we have to call the builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
in the Program.cs
file instead of builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
.
Step 3 : Update your handlers
The last step is to change the void requests returning Unit to only a return.In this case, the class handler is updated like this:
Previous code
public sealed class EditExistingCustomerHandler : IRequestHandler<EditExistingCustomerCommand, Unit>
{
...
public async Task<Unit> Handle(EditExistingCustomerCommand
request, CancellationToken cancellationToken)
{
var customerToUpdate = _mapper.Map<Customer>
(request.customerToUpdate);
await
_customerRepository.UpdateAsync(customerToUpdate);
return Unit.Value;;
}
}
MediatR version V12 code
public sealed class EditExistingCustomerHandler : IRequestHandler<EditExistingCustomerCommand>
{
...
public async Task Handle(EditExistingCustomerCommand
request, CancellationToken cancellationToken)
{
var customerToUpdate = _mapper.Map<Customer>
(request.customerToUpdate);
await
_customerRepository.UpdateAsync(customerToUpdate);
return;
}
}
Important Note : if you method is not async, the return is
return Task.CompletedTask
.
We can get more details about How to migrate to this version here
Recaps
On this topic, we learned that Upgrading to MediatR v12 is a straightforward process that requires updating your NuGet packages, mediator registration, handlers, requests, and responses. By following these steps, you can take advantage of the new features and improvements in v12 and keep your application up-to-date with the latest technologies.
If you enjoyed this article, please subscribe and follow me.
Top comments (1)
Thank you!
"we have to call the builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly())); in the Program.cs file instead of builder.Services.AddMediatR(Assembly.GetExecutingAssembly());"
almost gave up ;)