In our previous article, we have learned the below details.
- MediatR library and its implementation.
- What is CQRS
- Implement the simple Query Handler using MediatR.
- Implement a Query Handler with input parameter(s) using MediatR.
Please refer the below links for more details.
I will be using the same sample project which has been created in the previous articles.
For this demo, I have used the below tools
- VS 2022 Community Edition Version 17.4.0 – Preview 2.1
- .NET 6.0
- Swagger/Postman
- MediatR Library
In this tutorial, we are going to discuss how can we implement a Command Handler.
To begin with, let us go ahead and add a Folder “Commands” and add a class under the folder “Commands” as below.
The source can be downloaded from the GitHub.
using MediatorDemo.Library.Models;
using MediatR;
namespace MediatorDemo.Library.Commands {
public record AddStudentCommand(StudentModel request): IRequest < StudentModel > ;
}
Now, let us go ahead and add a Handler AddStudentHandler under “Handler” folder.
using MediatorDemo.Library.Commands;
using MediatorDemo.Library.Data;
using MediatorDemo.Library.Models;
using MediatR;
namespace MediatorDemo.Library.Handlers {
public class AddStudentHandler: IRequestHandler < AddStudentCommand, StudentModel > {
private readonly IDataRepository _dataRepository;
public AddStudentHandler(IDataRepository dataRepository) => (_dataRepository) = (dataRepository);
public Task < StudentModel > Handle(AddStudentCommand request, CancellationToken cancellationToken) {
return Task.FromResult(_dataRepository.AddStudent(request.request));
}
}
}
Now let us add an endpoint into the Controller class.
[HttpPost]
public async Task < StudentModel > Post(StudentModel model) {
return await _mediator.Send(new AddStudentCommand(model));
}
We have completed our coding part. Now, let us go ahead and execute the endpoint via Postman
Perfect! We have successfully completed the Command handler with input parameter.
How do we ensure the AddStudentHandler executed? Let us execute the GetStudentsListHandler
We could see that the new record has been successfully added into the existing Student List.
Thank you for reading my blog. Please leave your comments in the comment box below.