DEV Community

Cover image for Introduction to Command Query Responsibility Segregation (CQRS) -iFour
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

Introduction to Command Query Responsibility Segregation (CQRS) -iFour

What is API?

Before knowing what is CQRS first we know about API. In simple words API is like an interface that is a set of functions and methods which allow programmers to access its specific features and data of an application.

Features of Asp.Net Web API

  • It supports different MVC features like controllers, routing, model binders, action results, filter, IOC container, or dependency injection that makes it simpler and easier to develop.
  • We can create ASP.NET web API which is formatted by Web API's MediaTypeFormatter in XML or JSON or any other format which you want to add as MediaTypeFormatter.
  • It supports convention-based Create, Update, and Delete Actions from where it works with HTTP verbs like GET, POST, PUT and DELETE.
  • We can create WebAPI in different ways which are accepted and generatecontent which are not be object-oriented like the image or any other document files.
  • The ASP.NET Web API gives responses in the HTTP status code.
  • It can be hosted in the application or on IIS.

What is CQRS?

CQRS stands for "Command Query Responsibility Segregation". CQRS is a pattern which is described by Greg Young. Its main portion is the notion that you can use a different model to update information than the model you use to read information. For some situations, this separation is often valuable but beware that for many systems CQRS adds risky complexity.

The mainstream approach people use for interacting with a data system is to treat it as a CRUD data-store. By this, we mean that we have a model of some record structure where we will create new records, read it and update it, and delete records when we're done with them. In the simplest case, our interchange is all about storing and retrieving these records

As our needs become more sophisticated we steadily move far away from that model. We might want to seem at the knowledge during different types the record store, perhaps collapsing multiple records into one, or forming virtual records by combining information for different places.

Read More: Understanding Validation Tag Helpers In Asp.net Core

Benefits Of CQRS

Independentscaling

CQRS allows the read and write workloads to scale independently, and should output in fewer lock contentions.

Security

Command Query Responsibility Segregation is easier to confirm that only the right domain entities are performing writes on the data.

Separation of concerns

Differentiate the read and write side may result in models which are more maintainable and flexible. All hard business logic goes into the Write Model and the read model is easy to compare to the write model.

Simpler queries

By storing a materialized view within the read database, the applicationcan avoid complex joins when querying.

Let's start to allow CQRS with program

To Follow my example first of all you need to clone my project from my GitHub repository.

When your cloning completes from my Repository open the CQRSDemo.sln solution.

After Cloning my project code let's understand structure of solution
The solution is the ASP.NET core template with some manually included folders. In solution have two folders manually included Commands and Queries.

In command folder you will find the classes which implements the command part of the pattern and in queries folder you found the classes which is related to queries part of pattern.

Controllers

In the controller, you will find the PostController class in which has two methods first is Get () and the second is SavePost() method. You can see the Save method is implemented as a command, and the second one the Get method is implemented as a query.

The Code of the controller class is below.


  [ApiController]
    public class PostsController :ControllerBase
    {
        private readonlyIQueriesService _queries;
        private readonlyICommandService _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 asyncTask<actionresult> Get()
        {
            return (await _queries.GetAllPostId()).ToList();
        }
        // POST api/values
        [HttpPost]
        public void SavePost([FromBody] SavePostDto value)
        {
            _commands.SavePost(value.Title, value.Body);
        }
    }</actionresult>

Enter fullscreen mode Exit fullscreen mode

As you see, we build with constructor the query service and command service are done in this controller. Initially first we configure ASP.NET core dependency injection framework to handle all related situations.

In this controller the Get method calls the query service and savepost method calls the command service.As we know a query is do operation only Read-Only and other side command is do action which is modifies the state of system.

Now let's see how this service are implemented.

Commands Folder

It contains an interface which states what commands service is capable for basic implementation.

Below is the ICommandService interface:


public interface ICommandService
    {
        Task SavePost(string title, string body);
    }
public class CommandService :ICommandService
    {
        private readonlyBlogContext _context;
        public CommandService(BlogContext context)
        {
_context=context??throw new ArgumentNullException(nameof(context));
        }
        public async Task SavePost(string title, string body)
        {
            var post = new Post() { Title = title, Body = body };
            await _context.Posts.AddAsync(post );
            await _context.SaveChangesAsync();
            return post ;
        }
    }

Enter fullscreen mode Exit fullscreen mode

The implementation of this interface is based on Entity Framework Core which store data inside a SQL Service instance.

Wants to Talk with Our Highly Skilled .NET Core Developer? Contact now.

Queries

In Command folder you can see a IQueriesService which describes query service.


public interface IQueriesService
  {
  Task GetAllPostId();
  }

Enter fullscreen mode Exit fullscreen mode

IQueriesService interfacecontains a Task GetAllPostId(); method to get a unique identifiers in database.


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();
    return await conn.QueryAsync("SELECT Id FROM dbo.Posts;");
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

As you have seen the query and command are different and separated tech for read -only we use entity framework.

One of the best advantages of CQRS is we can build highly optimized read operation and differentiated the operations for a different data store.

Conclusion

We hope with this blog post you will fully understand CQRS pattern and how to implement it in API and allow it CQRS is a pattern. We do programming for commands and queries in different models it is use full for easy to implement and more optimized structure hard business logic is do in write model and read model is easy then write model.In short CQRS is pattern in which can easily read and write and side may result in models which are more maintainable and flexible.

Top comments (0)