简体   繁体   English

带有 .NET API 的 CQRS 模式 - 将请求 object 与命令/查询分开

[英]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:关于在 .NET API 中使用 CQRS 模式,我已经看到了一些示例,其中将请求直接反序列化为命令/查询,然后将其发送出去进行处理,如下所示:

[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:在其他示例中,使用某种 dto 或请求 object,然后将其馈送到命令/查询的构造函数中,如下所示:

[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.第一种方法对我来说更有吸引力,因为它少了一个 model 和代码行。 Is there a reason why you might use the second approach and separate the request object from the command object?您是否有理由使用第二种方法并将请求 object 与命令 object 分开?

Is there a reason why you might use the second approach and separate the request object from the command object?您是否有理由使用第二种方法并将请求 object 与命令 object 分开?

Yes - the domain model changes at a faster cadence than your publicly facing interface.是的 - 域 model 的变化速度比您面向公众的界面更快。

CreateOrderDto is an in memory representation of the request payload; CreateOrderDto是一个在 memory 中表示的请求负载; 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. CreateOrderCommand是 memory 中用于在应用程序和域 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.两个关注点之间的距离大大缩短,因此更容易协调对话两端的变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM