mercredi 28 novembre 2018

CQRS - Creating BaseCommandHandler using Mediatr in C#, ASP.net Core

So I learned about Mediatr created by Jimmy Bogard and it really amazed me how we achieve CQRS pattern using Mediatr.

I started to implement it in my application, and then I realized that I might have hundreds of Entities in my application, and for each Entity I am not sure about creating separate commands and queries, that would be just opposite of DRY. So I started writing base commands and handlers.

public abstract class CreateBaseCommand : IRequest
{    
}

public abstract class DeleteBaseCommand : IRequest
{
}  //... and so on.

And respective handlers.

public abstract class CreateBaseHandler : IRequestHandler<CreateBaseCommand>
{
}

public abstract class DeleteBaseCommandHandler : IRequestHandler<DeleteBaseCommand>
{
}//... and so on.

But I realised, I would still need separate commands for my domain entities, and they will have to derive from their Base commands respectively.

Then I though if I can just put all commands in one and have just one base handler.

    public abstract class BaseCommand : IRequest
    { 
       int CommandType
    }

    public abstract class BaseCommandHandler : IRequestHandler<BaseCommand>
    {
       public Task<Unit> Handle(BaseCommand request, CancellationToken cancellationToken)
       {
        if (CommandType == 0)
        {
            // Create entity
        }
        if (CommandType == 1)
        {
            // Update entity
        }//.. and so on
      }
    }

I was wondering if there is more efficient way to do this, I am not very convinced with idea of using CommandType and have one handle method to perform all CRUD operations.

Is this a good approach or should I have separate set of commands for each domain entity?

Any help and suggestions are appreciated.

2 commentaires:

  1. By using "if (CommandType == 0)" your BaseCommandHandler is aware of the derived handlers. Base classes should not know about details of the derived classes in OOP.

    You could create a:
    protected abstract Func RequestDelegate { get; }
    which the derived classes implement, and call this within your BaseCommandHandler.

    RépondreSupprimer
  2. Ce commentaire a été supprimé par l'auteur.

    RépondreSupprimer