MediatR: Two Handle methods in one QueryHandler class

77 Views Asked by At

I use MediatR library in my project. I'm wondeing if it is ok to have two Handle methods in one class? The reason I wanted to do that is that both methods use the shared code which shouldn't be moved to a separate QueryHandler. Here is example of my code:

public record GetOtherRoundsQuery() : IRequest<RoundDb[]>;

public record IsOtherRoundExist() : IRequest<bool>;

public class OtherRoundsQueryHandler : IRequestHandler<GetOtherRoundsQuery, RoundDb[]>, IRequestHandler<IsOtherRoundExist, bool>
{
    public Task<RoundDb[]> Handle(GetOtherRoundsQuery request, CancellationToken cancellationToken)
    {
        return GetQuery().ToArrayAsync();
    }

    public Task<bool> Handle(IsOtherRoundExist request, CancellationToken cancellationToken)
    {
        return GetQuery().AnyAsync();
    }

    private IQueryable<RoundDb> GetQuery()
    {
        //return a complex query implementation
    }
}
1

There are 1 best solutions below

0
Sascha Wolfgruber On

I would not do that. Going by SRP, every class should have one responsibility, and not more. I think simply because a part of the code is the same does not mean they should share the same code when the functionality is in essence different.

One of the biggest advantages of MediatR is the fact that every use-case can be isolated into its own request/handler "package". Implementing a Handler twice on the same class goes against that principle and muddies what the handlers primary purpose is.

Not to mention discoverability: Two handlers in the same class is something nobody ever expects when using mediatR. Request and Handler names not matching up can lead to confusion for other developers working on the project in the future. This is quite a small and situational issue, but should be considered nonetheless.

If you want to share the IQueryable for both requests, you can create a repository in your Infrastructure/DataAccess Project and return an IQueryable from there