Using The CQRS Pattern In C#

Introduction

In today’s article, we will look at the CQRS pattern. This stands for the Command and Query Responsibility Segregation (CQRS) pattern. We will look at what this pattern is. What are the advantages of using this pattern? When it should and should not be used, and finally, we will look at a sample implementation of this pattern in a C# application.

The CQRS Pattern

The Command and Query Responsibility Segregation (CQRS) pattern states that we must separate the operations for reading the data from the operations for writing or updating the data. This means that functions for reading and writing data are not kept in the same interface or class. The main advantages of doing this include:

  1. Separate teams can work on these operations
  2. Each can be made to scale according to their own needs. Write operations are mostly used much less than read operations
  3. Each can have their own security as per requirements
  4. Read operations can have a different architecture to support caching, conversions to data transformation objects as required by clients
  5. Write operations can include data validation. lookups etc.

However, do keep in mind that this pattern is better suited to larger applications where the requirements and load levels between read and write operations are different. For a simple and small application, the normal CRUD pattern, often auto-generated from ORM tools, is sufficient.

A simple implementation of the CQRS Pattern

We will now look at a simple implementation of the CQRS pattern in a C# .NET console application. This application will have two repositories. One for the read operations, although we will only have one operation for demo purposes and another for write operations. These repositories will be called by the respective middle-tier components. As the repositories, there will be one for queries (reads) and another for Commands (writes). This application has been created using the Visual Studio 2019 Community Edition, which is a free version.

We create a new console application in .NET Core 3.1, as shown below,

Using The CQRS Pattern In C#

Using The CQRS Pattern In C#

Using The CQRS Pattern In C#



The structure of the completed solution looks like the shown below:

Using The CQRS Pattern In C#

Let's first look at the two repositories (These are in the repositories folder)

The Commands (Write) repository

using ConsoleAppCQRSPattern.Models;  
namespace ConsoleAppCQRSPattern.Repositories {  
    public interface IEmployeeCommandsRepository {  
        void SaveEmployee(Employee employee);  
    }  
}  
using ConsoleApp CQRSPattern.Models;  
namespace ConsoleApp CQRSPattern.Repositories {  
    public class EmployeeCommandsRepository: IEmployeeCommandsRepository {  
        public void SaveEmployee(Employee employee) {  
            // Persist the employee record in a data store  
        }  
    }  
}  

Here we see that only write operations (in this case only one) are included.

The Queries (Read) repository

using ConsoleAppCQRSPattern.Models;  
namespace ConsoleAppCQRSPattern.Repositories {  
    public interface IEmployeeQueriesRepository {  
        Employee GetByID(int employeeID);  
    }  
}  
using System;  
using ConsoleAppCQRSPattern.Models;  
namespace ConsoleAppCQRSPattern.Repositories {  
    public class EmployeeQueriesRepository: IEmployeeQueriesRepository {  
        public Employee GetByID(int employeeID) {  
            // Get the employee record from a data store  
            // Below is for demo purposes only  
            return new Employee() {  
                Id = 100,  
                    FirstName = "John",  
                    LastName = "Smith",  
                    DateOfBirth = new DateTime(2000, 1, 1),  
                    Street = "100 Toronto Street",  
                    City = "Toronto",  
                    PostalCode = "k1k 1k1"  
            };  
        }  
    }  
} 

Here we see that only read operations (in this case only one) are included.

Next, we look at the two middle-tier components (These are in the Queries and Commands folders),

Queries (To read data)

using ConsoleAppCQRSPattern.DTOs;  
namespace ConsoleAppCQRSPattern.Queries {  
    public interface IEmployeeQueries {  
        EmployeeDTO FindByID(int employeeID);  
    }  
}  
using System;  
using ConsoleAppCQRSPattern.Repositories;  
using ConsoleAppCQRSPattern.DTOs;  
namespace ConsoleAppCQRSPattern.Queries {  
    public class EmployeeQueries {  
        private readonly IEmployeeQueriesRepository _repository;  
        public EmployeeQueries(IEmployeeQueriesRepository repository) {  
            _repository = repository;  
        }  
        public EmployeeDTO FindByID(int employeeID) {  
            var emp = _repository.GetByID(employeeID);  
            return new EmployeeDTO {  
                Id = emp.Id,  
                    FullName = emp.FirstName + " " + emp.LastName,  
                    Address = emp.Street + " " + emp.City + " " + emp.PostalCode,  
                    Age = Convert.ToInt32(Math.Abs(((DateTime.Now - emp.DateOfBirth).TotalDays) / 365)) - 1  
            };  
        }  
    }  
}  

Commands (To write data)

using ConsoleAppCQRSPattern.Models;  
namespace ConsoleAppCQRSPattern.Commands {  
    public interface IEmployeeCommands {  
        void SaveEmployeeData(Employee employee);  
    }  
}  
using ConsoleAppCQRSPattern.Models;  
using ConsoleAppCQRSPattern.Repositories;  
namespace ConsoleAppCQRSPattern.Commands {  
    public class EmployeeCommands: IEmployeeCommands {  
        private readonly IEmployeeCommandsRepository _repository;  
        public EmployeeCommands(IEmployeeCommandsRepository repository) {  
            _repository = repository;  
        }  
        public void SaveEmployeeData(Employee employee) {  
            _repository.SaveEmployee(employee);  
        }  
    }  
}  

Here we see that we have separate operation handling components. Two other classes are the main Employee class which mirrors our storage item and the Employee DTO class which is used by the Queries (Read) operations to return data in a shape required by the consuming client.

namespace ConsoleAppCQRSPattern.DTOs {  
    public class EmployeeDTO {  
        public int Id {  
            get;  
            set;  
        }  
        public string FullName {  
            get;  
            set;  
        }  
        public int Age {  
            get;  
            set;  
        }  
        public string Address {  
            get;  
            set;  
        }  
    }  
}  
using System;  
namespace ConsoleAppCQRSPattern.Models {  
    public class Employee {  
        public int Id {  
            get;  
            set;  
        }  
        public string FirstName {  
            get;  
            set;  
        }  
        public string LastName {  
            get;  
            set;  
        }  
        public DateTime DateOfBirth {  
            get;  
            set;  
        }  
        public string Street {  
            get;  
            set;  
        }  
        public string City {  
            get;  
            set;  
        }  
        public string PostalCode {  
            get;  
            set;  
        }  
    }  
}  

Finally, we call these operations from the main Program class. Please note that in this demo application, we create an instance of the repository directly. In a real-world scenario, we would probably use some dependency injection framework to do this.

using ConsoleAppCQRSPattern.Commands;  
using ConsoleAppCQRSPattern.Queries;  
using ConsoleAppCQRSPattern.Repositories;  
using System;  
namespace ConsoleAppCQRSPattern {  
    classProgram {  
        staticvoid Main(string[] args) {  
            // Command the Employee Domain to save data  
            var employeeCommand = new EmployeeCommands(new EmployeeCommandsRepository());  
            employeeCommand.SaveEmployeeData(new Models.Employee {  
                Id = 200, FirstName = "Jane", LastName = "Smith", Street = "150 Toronto Street", City = "Toronto", PostalCode = "j1j1j1", DateOfBirth = new DateTime(2002, 2, 2)  
            });  
            Console.WriteLine($ "Employee data stored");  
            // Query the Employee Domain to get data  
            var employeeQuery = new EmployeeQueries(new EmployeeQueriesRepository());  
            var employee = employeeQuery.FindByID(100);  
            Console.WriteLine($ "Employee ID:{employee.Id}, Name:{employee.FullName}, Address:{employee.Address}, Age:{employee.Age}");  
            Console.ReadKey();  
        }  
    }  
}  

When we run this application, we see the below output,

Using The CQRS Pattern In C#

Going for an interview, here are the Top C# Interview Questions Guaranteed to Help You Pass Your C# Interview.

Summary

In this article, we looked at the CQRS (Command and Query Responsibility Segregation) pattern and what are the advantages of using this pattern. The example given here is a simple one, but the main idea was to give an outline of how this pattern is to be implemented. The overall layout might be modified further to meet your specific requirement e.g. the repositories could be combined. However, as mentioned earlier, this pattern is better suited to larger applications where the requirements for read-and-write operations may vary or be overly complex. For simple CRUD operations, we might not need to implement this pattern. Happy Coding!


Similar Articles