Closed bancroftway closed 3 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());
}
}
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.
This issue was closed because it has been stalled for 14 days with no activity.
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?