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. ...
Join the DZone community and get the full member experience.
Join For FreeIn this blog post, we're going to explore a simple ASP.Net Core CQRS Web API 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.
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.
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 Save
method as a command.
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 its work done. In Startup, we configure the ASP.NET Core Dependency Injection framework to handle this situation.
The SavePost
method calls the command service and the Get()
method 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 worlds queries and commands 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.
Conclusion
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 technologies 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
Published at DZone with permission of Michele Ferracin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments