Skip to content

Conversation

@jbogard
Copy link
Collaborator

@jbogard jbogard commented Feb 13, 2023

I did not pull all the possible options from @remcoros 's samples. Just the basic couple options.

@jbogard
Copy link
Collaborator Author

jbogard commented Feb 13, 2023

This PR introduces the idea of notification publishers as a separate class to be injected into the Mediator class. Instead of only being able to override the PublishCore method in a derived class, this lets you inject your own implementation.:

public class Mediator : IMediator
{
    public Mediator(IServiceProvider serviceProvider) 
-        => _serviceProvider = serviceProvider;
+        : this(serviceProvider, new ForeachAwaitPublisher()) { }

+    public Mediator(IServiceProvider serviceProvider, INotificationPublisher publisher)
+    {
+        _serviceProvider = serviceProvider;
+        _publisher = publisher;
+    }

Two new publishing strategies added:

  • ForeachAwaitPublisher (the default, existing strategy)
  • TaskWhenAllPublisher - uses Task.WhenAll to publish

The publishing strategies now can accept the handler instance, for cases when ordering is needed:

+public interface INotificationPublisher
+{
+    Task Publish(IEnumerable<NotificationHandlerExecutor> handlerExecutors, INotification notification,
+        CancellationToken cancellationToken);
+ }
+ public record NotificationHandlerExecutor(object HandlerInstance, Func<INotification, CancellationToken, Task> HandlerCallback);

This required a breaking change in the PublishCore method in Mediator:

public class Mediator : IMediator {
-    protected virtual async Task PublishCore(IEnumerable<Func<INotification, CancellationToken, Task>> allHandlers, INotification notification, CancellationToken cancellationToken)
-    {
-        foreach (var handler in allHandlers)
-        {
-            await handler(notification, cancellationToken).ConfigureAwait(false);
-        }
-    }
+    protected virtual Task PublishCore(IEnumerable<NotificationHandlerExecutor> handlerExecutors, INotification notification, CancellationToken cancellationToken) 
+       => _publisher.Publish(handlerExecutors, notification, cancellationToken);
}

The notification publisher can be configured via MediatrServiceConfiguation:

+    public INotificationPublisher NotificationPublisher { get; set; } = new ForeachAwaitPublisher();
+    public Type? NotificationPublisherType { get; set; }

The NotificationPublisherType value overrides the instance property.

@remcoros
Copy link
Contributor

awesome!

@neozhu
Copy link

neozhu commented Feb 14, 2023

Will this feature be included in the next version? Very much looking forward to

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants