Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I register INotification with generics? #1024

Closed
grosch-intl opened this issue Apr 21, 2024 · 2 comments
Closed

How do I register INotification with generics? #1024

grosch-intl opened this issue Apr 21, 2024 · 2 comments

Comments

@grosch-intl
Copy link

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
Copy link

MattWood21 commented May 11, 2024

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:

  • The notification type can't be sealed due to boxing/unboxing constraints
  • The handler needs to the type of the notification, not the type inside the notification, though you can specify that it handles only notifications of the specified type you're looking for

@grosch-intl
Copy link
Author

Thank you, @MattWood21 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants