Mediator pattern

Mediator pattern

I have been criticized for implementing the mediator pattern in many companies. Everyone rightly want to use MediaR. I wrote the mediator pattern many years ago using reflection, after C# added functional programming I changed to the implementation below. I also have implemented using Java 8 chaining functions following a filter pipe to route request based on Type.

I was looking to leverage minimal external libraries as oppositive to use open source libraries as building block that leads me to this implementation.

Mediator pattern is commonly used to decouple components, whether is direct calls or message driven. I wrote a simple function that decouple components and leverage Dot Net Core service collection to route request.

Usage:

[HttpPost]
[ProducesResponseType(typeof(AddYardView), 200)]
[ProducesResponseType(typeof(ValidationStatus), 400)]
[ProducesResponseType(typeof(NotFound), 404)]
public async Task<IActionResult> Post([FromBody] AddYard addYard, CancellationToken token)
{
    return await _reqRouter.Route<AddYard, AddYardView>(addYard, token)
        .ConfigureAwait(false);
}        

Implementation:

public interface IReqRouter
{
    Task<ReqResult<TResult>> Route<TReq, TResult>(TReq command, CancellationToken token = default)
        where TReq : IReq;
}

public class ReqRouter : IReqRouter
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<ReqRouter> _logger;

    public ReqRouter(IServiceProvider serviceProvider,
        ILogger<ReqRouter> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }
    public async Task<ReqResult<TResult>> Route<TReq, TResult>(TReq command, CancellationToken token = default) where TReq : IReq
    {
        try
        {
            var handler = _serviceProvider.GetRequiredService<IReqService<TReq, TResult>>();
            if (handler == null)
            {
                return ReqResult<TResult>.ServerError(new ServerError { Message = "Handler not found" });
            }
            return await handler.Handle(command, token).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, ex.Message);
            return ReqResult<TResult>.ServerError(new ServerError { Message = ex.Message });
        }
    }
}        

要查看或添加评论,请登录

Yusbel Garcia Diaz的更多文章

  • Class for Handling Duplicate Message

    Class for Handling Duplicate Message

    Derek Comartin wrote a post about duplicate messages, covering most cases. I wrote a code back in 2023 for handling…

    1 条评论
  • ChatGPT -> Analysis of My Resume

    ChatGPT -> Analysis of My Resume

    I requested ChatGPT a career and impact summary along with role and industry I should target. I like the response: Chat…

  • Data access

    Data access

    Back in 2023 (Off work) and followed on 2024, I wrote a repository class that encapsulate LINQ queries. While this…

    1 条评论
  • Open to work

    Open to work

    I have been looking for work since the end of Dec 2024. Since then, I started taking courses and applying for work.

  • Software design patterns

    Software design patterns

    A personal opinion on design patterns. When to use them? Most code base follow design patterns, even those that are…

  • About me

    About me

    A generic answer to questions about personality and point of view. I'm looking to raise my case to secure a job.

  • Career

    Career

    Brief People who have stepped out of the workforce face a tremendous challenge in getting back to work, regardless of…

    2 条评论
  • Transactional outbox pattern

    Transactional outbox pattern

    Often times, we find ourselves developing a feature that needs to publish an event. On a few occasions, message…

  • Calculate Min and Max

    Calculate Min and Max

    Given an array of integers and a k value to remove k numbers from the array return Min and Max. Example: arr = [1, 5…

  • Decouple components with domain events

    Decouple components with domain events

    A technical building block for decoupling components. Most applications are required to have independent, discrete…

社区洞察