mardi 19 mai 2020

CQRS - Avoid switch case to call command handler

I am using CQRS design pattern. I have more than 15 command handlers corresponding to each event type. I want to avoid below switch case to call corresponding command handler based on event type.

Here is my Azure Function:

[FunctionName("ReceiveEvent")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            //log.LogInformation("ReceiveEvent HTTP trigger function started processing request.");

            //log.LogInformation($"Pushing Events to Azure Blob on storage account :-{CloudConfigurationManager.GetSetting("AzureWebJobsStorage")}");

            IActionResult actionResult = null;

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            var command = await _commandMapper.Map(requestBody);

            if (_commandValidator.Validate(req, command, ref actionResult))
            {
                switch (command.EventType)
                {
                    case EventType.CARD_BLOCK:
                        _cardBlockCommandHandler.Handle(command as CardBlockCommand);
                        break;
                    case EventType.CARD_CANCEL:
                        _cardCancelledCommandHandler.Handle(command as CardCancelledCommand);
                        break;
                    case EventType.CARD_UNBLOCK:
                        _cardUnBlockHandler.Handle(command as CardUnBlockCommand);
                        break;

                }
                //TODO
                return actionResult;
            }

Is there any better way to avoid this switch case?

Aucun commentaire:

Enregistrer un commentaire