Search code examples
c#.netcqrsmediatr

CQRS Pattern with .NET API - Separating the request object from the command/query


Concerning the use of the CQRS pattern in a .NET API I've seen some examples where the request is deserialized directly into the command/query and then it's sent off for handling, like this:

[HttpPost]
public async Task<IActionResult> CreateOrder(CreateOrderCommand command)
{
    var result = await _mediator.Send(command);
    return Ok(result);
}

In other examples, some kind of dto or request object is instead used and then fed into the constructor of the command/query, like this:

[HttpPost]
public async Task<IActionResult> CreateOrder(CreateOrderDto model)
{
    var command = new CreateOrderCommand(model.orderNumber, model.firstName...);
    var result = await _mediator.Send(command);
    return Ok(result);
}

The first approach looks more appealing to me as it's one less model and line of code. Is there a reason why you might use the second approach and separate the request object from the command object?


Solution

  • Is there a reason why you might use the second approach and separate the request object from the command object?

    Yes - the domain model changes at a faster cadence than your publicly facing interface.

    CreateOrderDto is an in memory representation of the request payload; the schema of which is something that is documented for client use. Making "breaking" changes to it is hard, because its a change that impacts all of your consumers.

    CreateOrderCommand is an in memory representation of data used to communicate between your application and your domain model. The distance between the two concerns is greatly reduced, and so it is a lot easier to coordinates changes at both ends of the conversation.