Skip to content

GetoXs/MediatR.Extensions.FluentValidation.AspNetCore

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MediatR.Extensions.FluentValidation.AspNetCore

GitHub Actions Status NuGet NuGet license

MediatR extension to the FluentValidation for .NET framework

Install

First you need to install packages Mediatr and FluentValidation, then follow the instructions 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(cfg => cfg.RegisterServicesFromAssembly(domainAssembly));

    //Add FluentValidation
    services.AddFluentValidation(new[] {domainAssembly});
    
    //Add other stuffs
    ...
}

Use

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