CQRS Using MediatR In .NET 6.0 - Part 2

In our previous article, we learned the below details.

  1. MediatR library and its implementation.
  2. What is CQRS
  3. Implement the simple Query Handler using MediatR.

Please refer to the CQRS-Part 1 for more details.

I will be using the same sample project which has been created in the previous article.

For this demo, I have used the below tools

  1. VS 2022 Community Edition Version 17.4.0 – Preview 2.1
  2. .NET 6.0
  3. Swagger/Postman
  4. MediatR Library

In this tutorial, we are going to discuss how can we implement a Query Handler with input parameters.

In our previous article, we have seen one endpoint “api/Student”, will return the entire students’ details.  Now we are going to implement an endpoint “api/Student/{id}” which will return student information based on the student’s id.

To begin with, let us go ahead and add a query class under the folder “Query” as below.

The source can be downloaded from GitHub.

using MediatorDemo.Library.Models;
using MediatR;

namespace MediatorDemo.Library.Queries
{
    public record GetStudentByIdQuery(int id):IRequest<StudentModel>;
  
}

Now, let us go ahead and add a Handler GetStudentByIdHandler under “Handler” folder.

using MediatorDemo.Library.Data;
using MediatorDemo.Library.Models;
using MediatorDemo.Library.Queries;
using MediatR;

namespace MediatorDemo.Library.Handlers
{
    public class GetStudentByIdHandler : IRequestHandler<GetStudentByIdQuery, StudentModel>
    {
        private readonly IDataRepository _repository;

        public GetStudentByIdHandler(IDataRepository repository)
        => (_repository) = (repository);
        public Task<StudentModel> Handle(GetStudentByIdQuery request, 
                                         CancellationToken cancellationToken)
        {
            return Task.FromResult(this._repository.GetStudentById(request.id));
        }
    }
}

Now let us add an endpoint into the Controller class.

[HttpGet("{id}")]
public async Task<StudentModel> Get(int id)
{
    return await _mediator.Send(new GetStudentByIdQuery(id));
}

We have completed our coding part. Now, is the time to execute the program and see how query with parameter would work.

CQRS Using MediatR In .NET 6.0

Fantastic!  We have successfully completed the Query handler with the input parameter.  In my upcoming article, I will be explaining the Command Handler using MediatR. Thank you for reading my article. Please leave your comments in the comment box below.