jbogard / MediatR

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

How do I register INotification with generics? #1024

Closed grosch-intl closed 2 months ago

grosch-intl commented 2 months ago

Is there any way to use notifications with generics? I have this:

public sealed record ApprovedNotification<T>(T Checklist) : INotification 
    where T : IChecklist;

public sealed class NotificationHandler<T> : INotificationHandler<ApprovedNotification<T>>
    where T : IChecklist

When I send the notification, the handler is never called. I'm guessing I need to do some type of explicit registration?

MattWood21 commented 2 months ago

You can use generics out of the box in almost the same way:

public record ApprovedNotification<T>(T Checklist) : INotification
    where T: IChecklist;

public sealed class NotificationHandler<T> : INotificationHandler<T>
    where T : ApprovedNotification<IChecklist>
{
    public Task Handle(T notification, CancellationToken cancellationToken)
    {
        // Do stuff
        return Task.CompletedTask;
    }
}

The differences:

grosch-intl commented 2 months ago

Thank you, @MattWood21 !