0

My Mediatr is using the SyncContinueOnException publish strategy, is there any way to run some validation before start the propagation?

Example:

_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;
    }
}
Alexandre
  • 7,004
  • 5
  • 54
  • 72

1 Answers1

0

Update Sorry, misread this originally!

One way to wrap the MediatR Publish behavior is to decorate the IMediator instance itself, either manually or with a library like Scrutor. You can add a marker interface to identify notifications that should pass through your validation logic, with any other events just flowing through to 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);
    }

    // ...
}

And in Startup, after the MediatR registration, using Scrutor's Decorate:

services.AddMediatR(typeof(Startup));
services.Decorate<IMediator, MediatorDecorator>();
Adam
  • 3,339
  • 1
  • 10
  • 15