Domain queries in CQRS

JontyMC picture JontyMC · Jan 6, 2010 · Viewed 9.3k times · Source

We are trying out CQRS. We have a validation situation where a CustomerService (domain service) needs to know whether or not a Customer exists. Customers are unique by their email address. Our Customer repository (a generic repository) only has Get(id) and Add(customer). How should the CustomerService find out if the Customer exists?

Answer

Kevin Swiber picture Kevin Swiber · Jan 7, 2010

Take a look at this blog post: Set based validation in the CQRS Architecture.

It addresses this very issue. It's a complex issue to deal with in CQRS. What Bjarte is suggesting is to query the reporting database for existing Customer e-mail addresses and issue a Compensating Command (such as CustomerEmailAddressIsNotUniqueCompensatingCommand) back to the Domain Model if an e-mail address was found. You can then fire off appropriate events, which may include an UndoCustomerCreationEvent.

Read through the comments on the above blog post for alternative ideas.

Adam D. suggests in a comment that validation is a domain concern. As a result, you can store ReservedEmailAddresses in a service that facilitates customer creation and is hydrated by events in your event store.

I'm not sure there's an easy solution to this problem that feels completely clean. Let me know what you come up with!

Good luck!