Skip to content

Instantly share code, notes, and snippets.

@mahpah
Created June 2, 2020 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahpah/b31347864fe7a9d0daa1cc566e7be338 to your computer and use it in GitHub Desktop.
Save mahpah/b31347864fe7a9d0daa1cc566e7be338 to your computer and use it in GitHub Desktop.
Use fluent validations to validate command and query
public class Startup
{
// ... etc
public void ConfigureServices(IServiceCollection services)
{
// ...etc
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationPipeline<,>));
services.AddValidatorsFromAssemblyContaining(typeof(Startup));
}
}
public class RequestValidationPipeline<TReq, TRes> : IPipelineBehavior<TReq, TRes>
{
private readonly IEnumerable<IValidator<TReq>> _validators;
public RequestValidationPipeline(IEnumerable<IValidator<TReq>> validators)
{
_validators = validators;
}
public Task<TRes> Handle(TReq request, CancellationToken cancellationToken, RequestHandlerDelegate<TRes> next)
{
var context = new ValidationContext(request);
var errors = _validators.Select(t => t.Validate(context))
.SelectMany(x => x.Errors)
.Where(x => x != null)
.ToList();
if (errors.Any())
{
throw new ValidationException(errors);
}
return next();
}
}
public class UpdateTenantBasicCommandValidator : AbstractValidator<UpdateTenantBasicInfoCommand>
{
public UpdateTenantBasicCommandValidator()
{
RuleFor(x => x.Id).NotEmpty();
RuleFor(x => x.Name).NotEmpty();
RuleFor(x => x.LearnerPortal).NotEmpty().MustBeUrl();
RuleFor(x => x.AdminPortal).NotEmpty().MustBeUrl();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment