MediatR icon indicating copy to clipboard operation
MediatR copied to clipboard

Add Support for Generic Handlers

Open zachpainter77 opened this issue 11 months ago • 0 comments

This PR essentially adds the required logic to register open generic request handlers.

For example:

//class to use as generic request type parameter
public class Pong
{
    string Message? { get; set; }
}

//generic request definition
public class GenericPing<T> : IRequest<T>
    where T : Pong 
{
    public T? Pong { get; set; }
}

//generic request handler
public class GenericPingHandler<T> : IRequestHandler<GenericPing<T>, T>
    where T : Pong
{
    public Task<T> Handle(GenericPing<T> request, CancellationToken cancellationToken) => Task.FromResult(request.Pong!);
}

//usage
var pong = _mediator.Send(new GenericPing<Pong>{ Pong = new() { Message = "Ping Pong" } });
Console.WriteLine(pong.Message); //would output "Ping Pong"

Huge fan of this library.. With that said.. I find it kind of tedious to have to create separate handlers for each thing, when the code is pretty much copy paste. Just the entity or type I'm working with has changed. I think it would be much easier to work with if we could essentially cut some corners by leveraging c# generics.

The only way you can do this without needing a third party library is use assembly scanning and register every single concrete implementation of the generic handlers. So that is what the code is doing.

I also added some tests to ensure the handlers were being registered.

**Note: this feature doesn't introduce any breaking changes. The feature is simply opt in by creating handlers like above.. if you don't want to use them then you can keep on using the library the same way without any hiccups.

zachpainter77 avatar Mar 23 '24 04:03 zachpainter77