Skip to content

Support for generic handlers #59

Open
@calledude

Description

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions