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

Support for generic handlers #59

Open
calledude opened this issue Apr 10, 2024 · 1 comment
Open

Support for generic handlers #59

calledude opened this issue Apr 10, 2024 · 1 comment

Comments

@calledude
Copy link

Given a structure that looks something like this

public abstract record Message { }

public record SomeMessage : Message { }
public record OtherMessage : Message { }

There is currently no way of handling these two "event types" under the same handler with generics.
In other words, this is illegal

[Handler]
public partial class MyHandler<T> where T : Message
{
    public static async ValueTask Handle(T notification, MyHandler<T> handler, CancellationToken cancellationToken)
    {
        await handler.Handle(notification, cancellationToken);
    }

    public async ValueTask Handle(T notification, CancellationToken cancellationToken)
    {
        // ....
    }
}

The following error can be observed in the build output.

error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

The general idea here is that MyHandler<T> would be registered in the IoC container as an unbound generic typeof(MyHandler<>).
This would be preferable as it would reduce boilerplate code, i.e. a separate handler for each event type that delegates to the same underlying handler type at the end.

@AlexTroshkin
Copy link

@calledude Is it possible to use the base message type as the first parameter in the HandleAsync method? Then through type mapping we can figure out how to process the message. The same would have to be done when supporting generalizations. Perhaps it will help?

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