MediatR.Extensions.FluentValidation.AspNetCore
MediatR.Extensions.FluentValidation.AspNetCore copied to clipboard
MediatR extension to FluentValidation for .NET framework
MediatR.Extensions.FluentValidation.AspNetCore
MediatR extension for FluentValidation using asp.net core
Install
A priori you need to install packages Mediatr and FluentValidation then continue below
Install with nuget
Install-Package MediatR.Extensions.FluentValidation.AspNetCore
Install with .NET CLI
dotnet add package MediatR.Extensions.FluentValidation.AspNetCore
How to use
Setup - Add configuration in startup
public void ConfigureServices(IServiceCollection services)
{
// Add framework services etc.
services.AddMvc();
var domainAssembly = typeof(GenerateInvoiceHandler).GetTypeInfo().Assembly;
// Add MediatR
services.AddMediatR(domainAssembly);
//Add FluentValidation
services.AddFluentValidation(new[] {domainAssembly});
//Add other stuffs
...
}
Use
Just to write down validators for IRequest
implementation. 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<Unit> Handle(GenerateInvoiceRequest request, CancellationToken cancellationToken)
{
// request data has been validated
...
}
}
More examples check FluentValidation docs: https://fluentvalidation.net/start