jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11.2k stars 1.18k forks source link

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

Closed bancroftway closed 3 months ago

bancroftway commented 6 months ago

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 commented 6 months ago

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());
    }
}
github-actions[bot] commented 4 months ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 14 days.

github-actions[bot] commented 3 months ago

This issue was closed because it has been stalled for 14 days with no activity.