jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11.14k stars 1.18k forks source link

MediatR generic notification handler not called #761

Closed jaytonic closed 2 years ago

jaytonic commented 2 years ago

Hi,

I'm starting to use MediatR's notification.

In one handler, I want to "log" every notification that comes through. According to what I found (https://stackoverflow.com/questions/70852634/mediatr-doesnt-handle-contravariant-notifications), I tried the following:

The NotificationHandler:

public class NotificationLogger<T> : INotificationHandler<T>
    where T : INotification
{
    private readonly ILogger<NotificationLogger<T>> _logger;
    public NotificationLogger(ILogger<NotificationLogger<T>> logger)
    {
        _logger = logger;
    }
    public Task Handle(T notification, CancellationToken cancellationToken)
    {
        _logger.LogTrace($"[{notification.GetType().Name}]: {notification} ");
        return Task.CompletedTask;
    }
}

One of my notification:

public class ServerStartedNotification : ISystemNotification
{
}
public class ISystemNotification : INotification
{
}

I register the notification handler:

app.Services.AddTransient(typeof(NotificationLogger<>));

In my Program.cs, I publish the notification just before waiting on the application:

using (IServiceScope? scope = app.Services.CreateScope())
{
    scope.ServiceProvider.GetRequiredService<IMediator>().Publish(new ServerStartedNotification()).Wait();
}
app.Run();

All my breakpoints gets hit, except the NotificationLogger.Handle.

Any idea why and what I could check?

KostetskyiYaroslav commented 2 years ago

I believe typing NotificationLogger<> was made on generic basis. So most likely we should specify what type we'd love to be resolved as NotificationLogger dependency.

After looking at example of MediatR Notification feature https://github.com/jbogard/MediatR/blob/master/test/MediatR.Tests/NotificationHandlerTests.cs I'd suggest trying overriding Handle method as example to follow the example.

Generally speaking we should confirm we follow MediatR library interfaces as actual behavior does look deviated. Hope it'd help if no - text me or reply below

Thanks