Created
June 2, 2020 10:16
-
-
Save mahpah/b31347864fe7a9d0daa1cc566e7be338 to your computer and use it in GitHub Desktop.
Use fluent validations to validate command and query
This file contains 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 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