How to handle set based consistency validation in CQRS?

一曲冷凌霜 提交于 2019-11-27 07:15:51

The solution I went with was to add a System aggregate root that could maintain a list of the current Facility names. When creating a new Facility, I use the System aggregate (only one System as a global object / singleton) as a factory for it. If the given facility name already exists, then it will throw a validation error.

This keeps the validation constraints within the domain and does not rely on the eventually consistent query store.

Rich Apodaca

Three approaches are outlined in Eventual Consistency and Set Validation:

  1. If the problem is rare or not important, deal with it administratively, possibly by sending a notification to an admin.
  2. Dispatch a DuplicateFacilityNameDetected event, which could kick off an automated resolution process.
  3. Maintain a Service that knows about used Facility names, maybe by listening to domain events and maintaining a persistent list of names. Before creating any new Facility, check with this service first.

Also see this related question: Uniqueness validation when using CQRS and Event sourcing

In this case, you may implement a simple CRUD style service that basically does an insert in a Sql table with a primary key constraint.

The insert will only happen once. When duplicate commands with the same value that should only exist one time hits the aggregate, the aggregate calls the service, the service fails the Insert operation due to a violation of the Primary Key constraint, throws an error, the whole process fails and no events are generated, no reporting in the query side, maybe a reporting of the failure in a table for eventual consistency checking where the user can query to know the status of the command processing. To check that, just query again and again the Command Status View Model with the Command Guid.

Obviously, when the command holds a value that does not exists in the table for primary key checking, the operation is a success.

The table of the primary key constraint should be only be used as a service, but, because you implemented Event sourcing, you can replay the events to rebuild the table of primary key constraint.

Because uniqueness check would be done before data writing, so the better method is to build a event-tracking service, which would send a notification when the process finished or terminated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!