Skip to content

Instantly share code, notes, and snippets.

@rvlieshout
Created July 7, 2011 12:21
Show Gist options
  • Save rvlieshout/1069393 to your computer and use it in GitHub Desktop.
Save rvlieshout/1069393 to your computer and use it in GitHub Desktop.
Our implementation of ICommandServiceInterceptor to evaluate validationrules before the command gets executed
public class ValidateCommandInterceptor : ICommandServiceInterceptor
{
private readonly IValidatorFactory _factory;
private readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public ValidateCommandInterceptor(IValidatorFactory validatorFactory = null)
{
_factory = validatorFactory ?? new AttributedValidatorFactory();
}
public void OnBeforeBeforeExecutorResolving(CommandContext context)
{
// Nothing
}
public void OnBeforeExecution(CommandContext context)
{
var validator = _factory.GetValidator(context.TheCommandType);
if (validator != null)
{
var result = validator.Validate(context.TheCommand);
if (!result.IsValid)
{
var message = string.Format("Command validation failed on command {0}{1}", context.TheCommandType, CreateValidationSummary(result));
_logger.ErrorFormat(message);
throw new CommandParameterValidationException(message);
}
}
}
public void OnAfterExecution(CommandContext context)
{
// Nothing
}
private static string CreateValidationSummary(ValidationResult result)
{
if (result.IsValid)
return string.Empty;
var sb = new StringBuilder(result.Errors.Count);
foreach (var failure in result.Errors)
{
sb.AppendLine();
sb.AppendFormat(" (*) Property {0}: {1}", failure.PropertyName, failure.ErrorMessage);
}
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment