I am new to using Mediator pattern, I could be using it the wrong way, however, I made the decision to use it since it was advertised to help in decoupling services and components and indeed, my application do have so many tightly coupled components. Some of them were in cyclic dependency.
What i did was creating a Command (IRequest) and Handler (IRequestHandler) for each method separated in a file for each.
Previously, when referencing direct components or classes, you could easily figure if there is a cyclic reference, but with Mediator, it is very hard and only detected when the action is invoked in runtime.
example code
using MediatR;
//Command
public record Car(int Count) : IRequest<string>;
//Handler
public class CarHandler(IMediator mediator) : IRequestHandler<Car, string>
{
public Task<string> Handle(Car request, CancellationToken ct)
{
return mediator.Send(new Driver(9), ct);
}
}
//Command
public record Driver(int Count) : IRequest<string>;
//Handler
public class DriverHandler(IMediator mediator) : IRequestHandler<Driver, string>
{
public Task<string> Handle(Driver request, CancellationToken ct)
{
return mediator.Send(new Car(5), ct);
}
}
the above code is just made up, but should give the idea that I am trying to explain. in my actual code, i had the situation of 4 requests calling each other and they end up in a loop causing a stackoverflow.
The Question: am I using the mediator pattern wrong? is it ok for a request handler to invoke other request through mediator, and how to prevent cyclic references?