我的Mediatr正在使用SyncContinueOnException publish strategy,在传播开始之前,有什么方法可以运行一些验证吗?
示例:
_mediatr.Publish(new MyNotification());
public class MyValidationHandler :
INotificationHandler<MyValidationHandler>
{
Task INotificationHandler<MyValidationHandler>.Handle(MyValidationHandler notification, CancellationToken cancellationToken)
{
// STOP propagation if some condition is false
}
}
public class FirstHandlers :
INotificationHandler<MyNotification>
{
Task INotificationHandler<MyNotification>.Handle(MyNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine("x");
return Task.CompletedTask;
}
}
public class SecondHandlers :
INotificationHandler<MyNotification>
{
Task INotificationHandler<MyNotification>.Handle(MyNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine("x");
return Task.CompletedTask;
}
}
答案 0 :(得分:0)
更新抱歉,原来是看错了!
包装MediatR Publish
行为的一种方法是手动装饰IMediator
实例本身,或使用Scrutor之类的库。您可以添加一个标记接口,以标识应通过验证逻辑传递的通知,而其他任何事件都将直接传递给MediatR。
public class MediatorDecorator : IMediator
{
private readonly IMediator _mediator;
public MediatorDecorator(IMediator mediator)
{
_mediator = mediator;
}
public Task Publish<TNotification>(TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification
{
if (notification is IValidatableNotification)
{
// Your validation behavior here
return Task.CompletedTask; // if the validation fails, respond as you'd like ...
}
return _mediator.Publish(notification, cancellationToken);
}
// ...
}
在启动中,在MediatR注册之后,使用Scrutor的Decorate
:
services.AddMediatR(typeof(Startup));
services.Decorate<IMediator, MediatorDecorator>();