CQRS by Example – Simple ASP.Net CORE implementation

In this blog post we’re going to explore a simple ASP.Net Core CQRS WebApi project. The code for this tutorial exposes a demonstrative API to manage a blog.


The source code is available on my GitHub account.

This post continues from the introduction post about CQRS.

Get started

To follow this tutorial the first thing we have to do is to clone or download the repository from GitHub.

When the clone is completed we open the IC6.TutorialCQRS.sln solution.

cqrs1.jpg

Solution structure

The solution is the typical ASP.Net Core template with some more folders. Inside the Commands folder we find the classes that implement the Command part of the pattern. Inside the Queries folder we find the classes related to the Queries part of the pattern.

cqrs2.jpg

Controllers

Inside the Controllers folder we find the PostController class with a Get() and a SavePost(…) method. The Get method is implemented as a query and the SaveMethod as a command.

cqrs4.jpg

The code of the class is the following:

[Route("api/[controller]")]
    [ApiController]
    public class PostsController : ControllerBase
    {
        private readonly IQueriesService _queries;
        private readonly ICommandService _commands;

        public PostsController(IQueriesService queries, ICommandService commands)
        {
            _queries = queries ?? throw new ArgumentNullException(nameof(queries));
            _commands = commands ?? throw new ArgumentNullException(nameof(commands));
        }

        // GET api/values
        [HttpGet]
        public async Task<ActionResult> Get()
        {
            return (await _queries.GetAllPostId()).ToList();
        }

        // POST api/values
        [HttpPost]
        public void SavePost([FromBody] SavePostDto value)
        {
            _commands.SavePost(value.Title, value.Body);
        }
    }

As we can see we inject with the constructor the command service and the query service that this controller needs to get his work done. In the Startup we configure the ASP Net Core Dependency Injection framework to handle this situation.

The SavePost method calls the command service and the Get() calls the query service.

We rember that a Query is a read-only operation while a Command is an action that modifies the state of our system.

Now we’ll look how these services are implemented.

Commands

The Commands folder contains an interface that states what our commands service is capable of and a basic implementation.

This is the ICommandService interface:

public interface ICommandService
    {
        Task SavePost(string title, string body);
    }

The SavePosts method is used to save a new post in our blog.

The CommandService class implements ICommandService.

public class CommandService : ICommandService
    {
        private readonly BlogContext _context;

        public CommandService(BlogContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task SavePost(string title, string body)
        {
            var newPost = new Post() { Title = title, Body = body };

            await _context.Posts.AddAsync(newPost);

            await _context.SaveChangesAsync();

            return newPost;
        }
    }

The implementation is based on Entity Framework Core that stores data inside a SQL Server instance.

Queries

The query service capabilities are described by the IQueriesService interface inside the Commands folder.

public interface IQueriesService
    {
        Task GetAllPostId();
    }

This interface exposes the GetAllPostId method to retrieve all the unique identifiers of the blog posts inside our database.

The QueriesService class implements this interface and it’s based on the Micro-ORM Dapper.

public class QueriesService : IQueriesService
    {
        private readonly string _connectionString;

        public QueriesService(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("message", nameof(connectionString));
            }

            _connectionString = connectionString;
        }

        public async Task GetAllPostId()
        {
            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

                return await conn.QueryAsync("SELECT Id FROM dbo.Posts;");
            }
        }
    }

As we can see the queries and the commands world are completely separeted and they use different technlogies.
We use EF to handle and modify data while we use the lightweight Dapper to make read-only operations.

This is one of the main advantes of the CQRS pattern. We can further evolve our architecture by creating database structures heavily optimized for read operations or by reading data in a different data store.

TL;DR

With this blog post we explored a basic CQRS implementation. Data read and write operations are performed in separated services with different technologies. In some scenarios we could also think to implement a polyglot persistence achitecture with a mix of techlogies to achieve the best performance for our application: we could have a NoSQL and traditional RDBMS working together and exploit the best of both worlds based on our specific needs.

Source code

GitHub – https://github.com/phenixita/TutorialCQRS

CQRS blog posts

  1. Introduction

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.