private async Task <CommandResponse> HandlerAsync <T>(T command) where T : class, ICommand { if (command == null) { throw new ArgumentNullException(nameof(command)); } CommandResponse response = default; try { using var scope = _serviceFactory.CreateScope(); var handler = scope.ServiceProvider.GetService <ICommandHandler <T> >(); response = await handler.HandleAsync(command); foreach (var @event in response.Events) { dynamic concreteObject = _mapper.Map(@event, @event.GetType(), @event.GetType()); _eventSender.PublishAsync(concreteObject); } } catch (Exception ex) { if (_onException == null) { throw; } _onException(ex); } return(response); }