0

I'm using MediatR to publish notifications.

I have defined a notification handler as follows:

public class TestNotificationHandler : INotificationHandler<TestNotification>, IWithinTransaction
{
    public Task Handle(TestNotification notification, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

Then I created a custom Mediatr publisher, as showcased here. What happens is that in the Publisher class, depending on the chosen strategy, a specific implementation is called that invokes the registered event handlers, for example, for SyncStopOnException strategy:

private async Task SyncStopOnException(IEnumerable<Func<Task>> handlers)
{
    foreach (var handler in handlers)
    {                                
        await handler().ConfigureAwait(false);                                
     }
 }

Indeed, in the foreach I get back the handler of the TestNotificationHandler correctly, and it is executed. So this works fine.

But now I want to filter on these handlers, so that only the ones implementing my custom IWithinTransaction interface are executed.

And this is where I have some trouble. Because the handler is of type System.Func.

So the question is: how can I find out whether the notification handler to which the handler belongs implements this interface? The only thing that comes close is handler.Target property, but I have no idea how to use it or to check whether it's implementing my interface.

enter image description here

Any hints would be great :)

L-Four
  • 13,345
  • 9
  • 65
  • 109

1 Answers1

0

I just found it.

private async Task SyncStopOnException(IEnumerable<Func<Task>> handlers)
    {
        foreach (var handler in handlers)
        {
            object target = handler.Target;
            if (target != null)
            {
                var xField = target.GetType().GetFields().Single(f => f.Name == "x");
                var xFieldValue = xField.GetValue(target);
                if (xFieldValue as IWithinTransaction != null)
                {

                }
            }

            await handler().ConfigureAwait(false);                                
        }
    }
L-Four
  • 13,345
  • 9
  • 65
  • 109