Immediate.Handlers icon indicating copy to clipboard operation
Immediate.Handlers copied to clipboard

Support for generic handlers

Open calledude opened this issue 10 months ago • 0 comments

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.

calledude avatar Apr 10 '24 17:04 calledude