Created
July 7, 2011 12:21
-
-
Save rvlieshout/1069393 to your computer and use it in GitHub Desktop.
Our implementation of ICommandServiceInterceptor to evaluate validationrules before the command gets executed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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