Add validation to a MediatR behavior pipeline?

后端 未结 2 859
误落风尘
误落风尘 2021-02-02 10:28

I\'m using ASP.NET Core, the built-in container, and MediatR 3 which supports \"behavior\" pipelines:

public class MyRequest : IRequest
{
    // ..         


        
2条回答
  •  难免孤独
    2021-02-02 11:20

    The process is exactly the same, you just have to change the interface to use the new IPipelineBehavior interface.

    public class ValidationBehavior : IPipelineBehavior
        where TRequest : IRequest
    {
        private readonly IEnumerable> _validators;
    
        public ValidationBehavior(IEnumerable> validators)
        {
            _validators = validators;
        }
    
        public Task Handle(TRequest request, RequestHandlerDelegate next)
        {
            var context = new ValidationContext(request);
            var failures = _validators
                .Select(v => v.Validate(context))
                .SelectMany(result => result.Errors)
                .Where(f => f != null)
                .ToList();
    
            if (failures.Count != 0)
            {
                throw new ValidationException(failures);
            }
    
            return next();
        }
    }
    

    For the validators, you should register all the validators as IValidator in the built-in container so they'll be injected in the behavior. If you don't want to register them one by one, I suggest that you have a look at the great Scrutor library that brings assembly scanning capabilities. This way it'll find your validators itself.

    Also, with the new system, you don't use the decorator pattern anymore, you just register your generic behavior in the container and MediatR will pick it up automatically. It could look something like:

    var services = new ServiceCollection();
    services.AddMediatR(typeof(Program));
    services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
    var provider = services.BuildServiceProvider();
    

提交回复
热议问题