Type implementing INotificationHandler and IRequestHandler is called more than once on Notification
See original GitHub issueI have a type MySuperHandler
that implements an INotificationHandler<SomethingHappened>
and also an IRequestHandler<ShouldItHappen, true>
.
The type is registered through MediatR.Extensions.Autofac.DependencyInjection (3.0.0) once at startup using builder.AddMediatR(typeof(Program).Assembly);
When I publish the Notification SomethingHappened
using
await _mediator.Publish(new SomethingHappened());
the Handle method for SomethingHappened
of MySuperHandler
gets called twice.
Implementing multiple different INotificationHandler on a type is no problem. The Handle will only be called once.
Removing the interface IRequestHandler<ShouldItHappen,true> from the type, solves the problem and the method gets only called once.
Is this a bug within Mediatr? Is it not allow to implement an INoficationHandler and IRequestHandler on the same type?
public class MySuperHander : INotificationHandler<SomethingHappened>, IRequestHandler<ShouldItHappen,bool> {
public async Task Handle(SomethingHappened notification, CancellationToken cancellationToken) {
Console.WriteLine("It has happened");
}
public async Task<bool> Handle(ShouldItHappen request, CancellationToken cancellationToken) {
return true;
}
}
public class ShouldItHappen : IRequest<bool> { }
public class SomethingHappened : INotification { }
This will print out “It has happened” twice. when calling await _mediator.Publish(new SomethingHappened());
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
I think you are right. Currently dumping autofac registrations and I think I saw MySuperHandler registered more than once for INotificationHandler. Let me check that
I would say in general when keeping SOLID in mind you would want to isolate responsibility of the notification handlers to their own classes. Any shared functionality between them could be offloaded to an injected dependent service if necessary.