79298700

Date: 2024-12-21 01:04:41
Score: 0.5
Natty:
Report link

The mediator behavioral pattern is one that simply prescribes that you restrict direct communication between objects and force them to talk via a mediator object.

In your example, both the handler and service style shown actually follow the mediator pattern. In both, you are preventing direct communication between the controller and the repo, forcing them to go through the MediatR handler or service, respectively.

However, the purpose of the mediator object in the mediator pattern is to reduce dependencies between those objects, and other objects that may need to deal with them.

Note, however, that the mediator pattern is a behavioral pattern.

MediatR is a .NET implementation of the mediator pattern, allowing you to ensure this behavior is followed in your application. But, it can also help with facilitating other patterns, such a the adapter, facade, or proxy structural design patterns. The handlers are a kind of mini-service as well, but I encourage only using mediator handlers as a way of handling communication as their single purpose.

The service, as you included it in your example, has a different purpose in most designs. It's purpose is to provide a place for you to put business logic. Of course, often for simple 'GetAll' kind of endpoints, there is no business logic at the start, so we just have it there as a 'just in case', but really, you could just call the repo from your controller and save yourself some code and complexity. But, if you were to implement the mediator pattern as you have above, when you DO need to add business logic in there, you can then have the handler call a service instead of the repo, and the controller would be none the wiser and require zero changes (in theory). In true mediator implementation, the service wouldn't call the repo either, but rather the go back through the mediator get the info it needs from the repo, too.

Refactoring Guru has some good information on the various patterns and their uses.

https://refactoring.guru/design-patterns/mediator

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Low reputation (1):
Posted by: Steven Dove