Mediator icon indicating copy to clipboard operation
Mediator copied to clipboard

Support generic handlers

Open Atulin opened this issue 3 months ago • 0 comments

I switched from MediatR to Mediator recently, for sourcegen instead of reflections. Alas, it doesn't seem to support generic handlers, and I have a specific use case for them:

public sealed record Command<T>(...) : IRequest<ActionResult> where T : BaseModel, IBlockableContent;

public class Handler<T>(ApplicationDbContext context) : BaseHandler, IRequestHandler<Command<T>, ActionResult>
    where T : BaseModel, IBlockableContent
{
    public async ValueTask<ActionResult> Handle(Command<T> request, CancellationToken cancellationToken)
    {
        // snip
        var res = await context.Set<T>() // here's where the generic is important
            .Where(i => i.Id == itemId)
            .ExecuteUpdateAsync(i => i.SetProperty(p => p.ContentBlock, cb), cancellationToken);
        // snip
    }
}
[HttpPost("story")]
public async Task<ActionResult> BlockStory(BlockContent.Command<Story> data)
    => await mediator.Send(data);

[HttpPost("chapter")]
public async Task<ActionResult> BlockChapter(BlockContent.Command<Chapter> data)
    => await mediator.Send(data);

[HttpPost("blogpost")]
public async Task<ActionResult> BlockBlogpost(BlockContent.Command<Blogpost> data)
    => await mediator.Send(data);

Atulin avatar Mar 03 '24 20:03 Atulin