Implementing CQRS And Mediator Patterns With ASP.NET Core Web API


CQRS Pattern

The Command Query Responsibility Segregation (CQRS) pattern is a software architectural pattern that separates the responsibilities of reading data (queries) from the responsibilities of modifying data (commands) into distinct components. CQRS aims to improve the scalability, performance, and maintainability of an application by allowing different models and optimizations for reading and writing data. In a traditional monolithic application, the same model is often used for both reading and writing data. This can lead to challenges in optimizing and scaling the application for different use cases.

Mediator Pattern

The Mediator Pattern is a behavioral design pattern that promotes loose coupling between components by centralizing communication between them. It defines an object (the mediator) that encapsulates communication and coordination between multiple objects (colleagues), allowing them to interact without having direct references to each other. The Mediator Pattern helps reduce direct dependencies between components, making the system more maintainable and easier to extend.

Implementing the Command Query Responsibility Segregation (CQRS) and Mediator patterns in an ASP.NET Core Web API can help improve the organization, scalability, and maintainability of your application. Here’s a step-by-step guide with a code example:

  1. Create a New ASP.NET Core Web API Project:
    Use the following command to create a new ASP.NET Core Web API project:
   dotnet new webapi -n CQRSAndMediatorDemo
   cd CQRSAndMediatorDemo
  1. Install NuGet Packages:
    Install the necessary NuGet packages for CQRS and Mediator patterns:
   dotnet add package MediatR
   dotnet add package AutoMapper
  1. Define Commands and Queries:
    Create separate classes for commands and queries. In CQRS, commands are used for actions that modify data, and queries are used to retrieve data.
   // Commands
   public class CreateProductCommand : IRequest<ProductDto>
       public string Name { get; set; }
       public decimal Price { get; set; }

   // Queries
   public class GetProductsQuery : IRequest<List<ProductDto>>
  1. Create Command and Query Handlers:
    Create handler classes for commands and queries. These handlers will perform the necessary actions based on the commands and queries.
   public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, ProductDto>
       // Implement handler logic to create a product

   public class GetProductsQueryHandler : IRequestHandler<GetProductsQuery, List<ProductDto>>
       // Implement handler logic to retrieve products
  1. Register Services and Mediator:
    In your Startup.cs file, configure services and register the Mediator pattern:
   using MediatR;

   public void ConfigureServices(IServiceCollection services)
       // Other configurations

       // Register MediatR

       // Add AutoMapper configuration if needed
  1. Create Controllers:
    Create controllers to handle HTTP requests and communicate with the Mediator for command and query execution.
   public class ProductsController : ControllerBase
       private readonly IMediator _mediator;

       public ProductsController(IMediator mediator)
           _mediator = mediator;

       public async Task<IActionResult> CreateProduct(CreateProductCommand command)
           var productDto = await _mediator.Send(command);
           return CreatedAtAction(nameof(GetProduct), new { id = productDto.Id }, productDto);

       public async Task<IActionResult> GetProducts()
           var products = await _mediator.Send(new GetProductsQuery());
           return Ok(products);
  1. Run the Application:
    Start the application using the following command:
   dotnet run

You can use tools like curl, Postman, or a browser to interact with the API endpoints.

This example demonstrates a basic implementation of the CQRS and Mediator patterns in an ASP.NET Core Web API. Keep in mind that this is a simplified example, and you can extend and customize it to match your specific application requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *