【发布时间】:2020-07-12 11:53:08
【问题描述】:
首先,我将Fluent Results 与Mediatr 和Fluent Validation 结合使用
我最初关注this article,但我没有重新发明轮子,而是开始在我的 Fluent 验证管道中使用 FluentResults。基本上来自我的 CQRS 查询的所有响应都包含在 Result 对象中,这避免了将异常作为错误处理方法。
但是,我无法让我的管道发挥出色:
public class ValidationPipeline<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TResponse : class
where TRequest : IRequest<TResponse>
{
private readonly IValidator<TRequest> _compositeValidator;
public ValidationPipeline(IValidator<TRequest> compositeValidator)
{
_compositeValidator = compositeValidator;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var result = await _compositeValidator.ValidateAsync(request, cancellationToken);
if (!result.IsValid)
{
Error error = new Error();
var responseType = typeof(TResponse);
foreach (var validationFailure in result.Errors)
{
Log.Warning($"{responseType} - {validationFailure.ErrorMessage}");
error.Reasons.Add(new Error(validationFailure.ErrorMessage));
}
// This always returns null instead of a Result with errors in it.
var f = Result.Fail(error) as TResponse;
return f;
}
return await next();
}
}
我还必须以某种方式将 Result 对象转换回 TResponse,其中 TResponse 始终是 Result
非常感谢任何建议!
编辑:
Autofac 集成
protected override void Load(ContainerBuilder builder)
{
var assembly = Assembly.GetExecutingAssembly();
// MediatR
builder.AddMediatR(assembly);
// Register the Command's Validators (Validators based on FluentValidation library)
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
.AsImplementedInterfaces();
// Register all the Command classes (they implement IRequestHandler) in assembly holding the Commands
builder.RegisterAssemblyTypes(assembly)
.AsClosedTypesOf(typeof(IRequestHandler<,>));
// Register Behavior Pipeline
builder.RegisterGeneric(typeof(ValidationPipeline<,>)).As(typeof(IPipelineBehavior<,>));
}
【问题讨论】:
-
这是否编译并运行?但只是一直返回
f为空? -
如果你用具体类 Result 替换 TResponse 的使用(既然你说 Result 将始终用于 Result,会发生什么?
-
@AnnL。感谢您的评论,我确实尝试过,当我将“类”更改为“结果”时,管道停止被调用。我用可能相关的 AutoFac 配置更新了帖子
-
这很有趣。我想知道:这听起来像
TResponse并不是真正的Result对象,或者它可能没有意识到它是。能否调试并在转换为TResponse的行处下断点,以便在运行时检查TResponse的具体类型是什么? -
@AnnL。好建议,我试过了,TResponse 是一个带有传递 T 参数的 Result 对象。我添加了一个答案,解释了我是如何找到解决方法的。
标签: c# asp.net-core cqrs fluentvalidation mediatr