Commands, Handlers and Validators

I have been going back and forth between how to do validation in this scenario:

  1. Create a command
  2. Get a command handler
  3. Handle the command by executing the handler – Validation, domain entity creation and saving it by the repository happens here.

First off, I will refer to Udi Dahan’s article on generic validation.

I started thinking about validation like this; validate the command properties, if valid, create object, save it to the repository and raise a domain event. The validator objects would validate the command before the entity is even created.

Then I revised my solution to creating the entity, validate the entity in the context of the command, if valid, save it to repository and raise the event.

I think the latter seems more natural since validating an entity in the context of a command is what the validation should be. After all, command’s purpose is to do something with the entity it is eventually going to operate on…

    public class NewTreatmentCenterValidator : IValidator<TreatmentCenter, CreateNewTreatmentCenterCommand>
        #region Implementation of IValidator<in TreatmentCenter,CreateNewTreatmentCenterCommand>

        public ValidationResult Validate(TreatmentCenter obj)
            var result = new ValidationResult();

            if (obj.TreatmentCenterID.Equals(Guid.Empty))
                result.Add("TreatmentCenterID", "Treatment center should have an id.");

            // other validation implementations here...

            return result;


I can sleep now…