Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: Can multiple MediatR handlers be packaged into a single class #1029

Open
bancroftway opened this issue May 9, 2024 · 1 comment

Comments

@bancroftway
Copy link

One of our Architects has objected to the usage of CQS pattern as he thinks that this results in file bloat, because of single class per-handler.

Is there a way to package multiple handlers in a single class (not file), sort of like Wolverine does?

@9kbx
Copy link

9kbx commented May 17, 2024

Yes, multiple MediatR handlers can be packaged into a single class, but this approach is generally discouraged as it goes against the Single Responsibility Principle (SRP). Each handler should ideally handle only one request type to keep your code clean, maintainable, and aligned with SOLID principles. However, if you have specific reasons for combining them, you can do it by implementing multiple handler interfaces in a single class.

Here's an example of how you could implement multiple MediatR handlers within a single class:

public class ListProductsQueryHandler
    : IRequestHandler<ListProductsQuery, List<ProductDto>>,
        IRequestHandler<ListProductsQuery2, object>
{
    // Handler1
    public Task<List<ProductDto>> Handle(
        ListProductsQuery request,
        CancellationToken cancellationToken
    )
    {
        // todo
        return Task.FromResult(
            Enumerable
                .Range(1, 5)
                .Select(index => new ProductDto(Guid.NewGuid(), $"MyName{index}", "test", index))
                .ToList()
        );
    }

    // Handler2
    public Task<object> Handle(ListProductsQuery2 request, CancellationToken cancellationToken)
    {
        // todo
        return Task.FromResult(DateTime.Now.ToString());
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants