Without MediatR - Notifications, Custom Notification Publisher

Arialdo Martini — 29/08/2023 — C# MediatR

Notifications - Custom Notification Publisher

With MediatR

When publishing notifications, it is possible to pass MediatR an instance of INotificationPublisher that controls the way the handlers are invoked:


_container = new Container(cfg =>
{
    cfg.For<IMediator>().Add(s => new Mediator(s, new CustomNotificationPublisher()))
}

class CustomNotificationPublisher : INotificationPublisher
{
    async Task INotificationPublisher.Publish(IEnumerable<NotificationHandlerExecutor> handlerExecutors, INotification notification, CancellationToken cancellationToken)
    {
        foreach (var handler in handlerExecutors)
        {
            await handler.HandlerCallback(notification, cancellationToken).ConfigureAwait(false);
        }
    }
}

code

Without MediatR

This it no special case: it’s the implementation of the composite we already saw in handling notifications without MediatR.

FAQs

Why should the OOP implementation be preferrable?

Answer
A MediatR Custom Notification Publisher

With the OOP approach:

  • this is no special case
  • different custom notification publishers can be used for different handlers
  • it works for both notifications and reqeusts.

Comments

GitHub Discussions