gpt4 book ai didi

c# - 向 MediatR 行为管道添加验证?

转载 作者:IT王子 更新时间:2023-10-29 04:44:15 34 4
gpt4 key购买 nike

我正在使用内置容器 ASP.NET Core 和支持 "behavior" pipelines 的 MediatR 3 :

public class MyRequest : IRequest<string>
{
// ...
}

public class MyRequestHandler : IRequestHandler<MyRequest, string>
{
public string Handle(MyRequest message)
{
return "Hello!";
}
}

public class MyPipeline<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
var response = await next();
return response;
}
}

// in `Startup.ConfigureServices()`:
services.AddTransient(typeof(IPipelineBehavior<MyRequest,str‌​ing>), typeof(MyPipeline<MyRequest,string>))

我需要管道中的 FluentValidation 验证器。在 MediatR 2 中,一个 validation pipeline was created thus :

public class ValidationPipeline<TRequest, TResponse>
: IRequestHandler<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{

public ValidationPipeline(IRequestHandler<TRequest, TResponse> inner, IEnumerable<IValidator<TRequest>> validators)
{
_inner = inner;
_validators = validators;
}

public TResponse Handle(TRequest message)
{
var failures = _validators
.Select(v => v.Validate(message))
.SelectMany(result => result.Errors)
.Where(f => f != null)
.ToList();
if (failures.Any())
throw new ValidationException(failures);
return _inner.Handle(request);
}

}

现在如何为新版本执行此操作?如何设置要使用的验证器?

最佳答案

过程完全相同,您只需更改界面即可使用新的IPipelineBehavior<TRequest, TResponse>。界面。

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;

public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}

public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> 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();
}
}

对于验证器,您应该将所有验证器注册为 IValidator<TRequest>在内置容器中,以便将它们注入(inject)行为中。如果你不想一一注册,建议你看看大神Scrutor library这带来了程序集扫描功能。这样它会自己找到你的验证器。

此外,在新系统中,您不再使用装饰器模式,您只需在容器中注册您的通用行为,MediatR 将自动获取它。它可能看起来像:

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

关于c# - 向 MediatR 行为管道添加验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42283011/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com