What should I validate? For me, this was the question for the most of the time (and now yet). Should I validate commands or aggregates? For who, like me, is used with n-layered architectures the answer is pretty simple: Aggregates (aka Entities). But that is something controversial in CQRS world. Or, better to say, in CQRS+ES world. Infact with ES the main idea is to have an only-append event store that should be accessed just to retrieve Aggregates by ID or to save them. Nothing more. So how could I validate a single aggregate without the capability to read a set of aggregates? The answer is: I cannot. I read a lot about set validation and the most valuable reading, for me, is the Greg Young’s one. He says that we should to do an “eventual consistent validation”, i.e. a validation based on eventual consistent data. So, as defined in the previous diagram, I realized a set of Command validators that could perform its own check. I put this code as before the command handling, because the purpose of this kind of validation is to check that the command is valid from business point of view.
Let’s see some code. First of all, I’ve used a very flexible library to do this kind of command validation: FluentValidation. It gave me the ability to check for simple and complex rules, always having a very readable and maintainable code.
This is a sample code for an eventual consistent set validation:
As everywhere in my code, Castle Windsor resolves the necessary dependency for me. The same structure is good for consistent validation (aka validation based on Domain Repository).
So far so good. Now I use these command validators in the same way I use command handlers:
- Create a Validator Typed Factory
- Register the typed factory in DI container
- Call the factory and the validation as before the command handling