我的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;
}
}发布于 2020-05-23 05:56:58
更新很抱歉,最初是误读的!
包装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>();https://stackoverflow.com/questions/61963128
复制相似问题