MediatR extension to the FluentValidation for .NET framework
First you need to install packages Mediatr and FluentValidation, then follow the instructions below
Install-Package MediatR.Extensions.FluentValidation.AspNetCore
dotnet add package MediatR.Extensions.FluentValidation.AspNetCore
public void ConfigureServices(IServiceCollection services)
{
// Add framework services etc.
services.AddMvc();
var domainAssembly = typeof(GenerateInvoiceHandler).GetTypeInfo().Assembly;
// Add MediatR
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(domainAssembly));
//Add FluentValidation
services.AddFluentValidation(new[] {domainAssembly});
//Add other stuffs
...
}
Implement validator for your IRequest
objects. Validation will be executed before handling IRequestHandler
.
public class GenerateInvoiceValidator : AbstractValidator<GenerateInvoiceRequest>
{
public GenerateInvoiceValidator()
{
RuleFor(x => x.Month).LowerThan(13);
// etc.
}
}
public class GenerateInvoiceRequest : IRequest
{
public int Month { get; set; }
}
public class GenerateInvoiceRequestHandler : IRequestHandler<GenerateInvoiceRequest>
{
public async Task Handle(GenerateInvoiceRequest request, CancellationToken cancellationToken)
{
// request data has been validated
...
}
}
More examples check FluentValidation docs: https://fluentvalidation.net/start