public virtual ValidationResult Execute <T>(T command) where T : ICommand
        {
            var validator = Dispatcher.GetValidator(command);
            var result    = validator.Validate(command as dynamic);

            if (result != null && !result.IsValid)
            {
                return(result);
            }

            var handler = Dispatcher.GetHandler(command);

            if (handler == null)
            {
                throw new
                      CommandHandlerNotFoundException(
                          $"no handler found for {command.GetType().Name} command");
            }

            try
            {
                handler.Handle(command);

                result = new ValidationResult
                {
                    IsValid = true
                };
            }
            catch (Exception e)
            {
                if (result == null)
                {
                    return(null);
                }

                result.IsValid = false;
                // ReSharper disable once MergeConditionalExpression
                result.ErrorMessages.Add(JsonConvert.SerializeObject(e));
            }

            return(result);
        }
Exemplo n.º 2
0
        public void Execute(IEnumerable <ICommand> commands)
        {
            foreach (var command in commands)
            {
                var validator        = _dispatcher.GetValidator(command);
                var validationResult = validator.Validate(command);

                if (!validationResult.IsValid)
                {
                    throw new CommandValidationException(validationResult.ErrorMessages);
                }

                var handler = _dispatcher.GetHandler(command);
                handler.Handle(command);
            }
        }