I’m having a very strange issue with decorator pattern using MediatR (12.4.0) and Autofac (8.0.0) but I really cannot understand wether the problem is concerning Autofac, MediatR or (more probably) my code…
Basically I have a custom wrapper around INotification:
// My custom notification wrapping the event
public interface IEventNotification<TEvent> : INotification
where TEvent : IEvent
{
TEvent Event { get; init; }
}
that is handled by this interface
// The custom Notification Handler.
public interface IEventNotificationHandler<TEvent> : INotificationHandler<IEventNotification<TEvent>>
where TEvent : IEvent
{
}
My requirement (somewhat simplified) are
- There are some known events (implementations of IEvent interface).
- The application will raise events using mediatr to publish an instance implementing the INotification interface (this will be created from generics during runtime).
- The events are handled by some handlers. In some cases there are multiple handlers per event.
My goal is to define the handlers by simply implementing IEventNotificationHandler.
Such handlers need to be decorated as per example code.
Now, my code is working as expected until I introduce the decorator for the event handlers like this one
public class CustomNotificationHandlerDecorator<TDomainEvent> : IEventNotificationHandler<TDomainEvent>
where TDomainEvent : IEvent
{
private readonly INotificationHandler<IEventNotification<TDomainEvent>> _decorated;
public CustomNotificationHandlerDecorator(IEventNotificationHandler<TDomainEvent> decorated)
{
_decorated = decorated;
}
public Task Handle(IEventNotification<TDomainEvent> notification, CancellationToken cancellationToken)
{
Console.WriteLine("I am the custom decorator!");
_decorated.Handle(notification, cancellationToken);
Console.WriteLine("Decorator job completedn");
return Task.CompletedTask;
}
}
At this point, for a given event, the decorator is applied only to one of the declared handlers and the handlers itself is called multiple times!
This is somewhat difficult to explain, so I crafted a fully functional but yet simple example on dotnetfiddle:
https://dotnetfiddle.net/5sIGzj
As you can see, only the SecondEventNotificationHandler is called (and decorated) twice.
If the line 155 builder.RegisterGenericDecorator(typeof(CustomNotificationHandlerDecorator<>),typeof(INotificationHandler<>));
is commented out, the two event handlers are called as expected, (but the decorator is obviously not called).