Esempio n. 1
0
        public void Dispatch <C>(C command)
            where C : CommandBase
        {
            try
            {
                // Log the fact that we received a command
                _eventRepo.PersistEvent(new CommandReceivedEvent(command));

                // Load the Aggreage
                var initAggregate = _aggreageFactory.Init(command.AggregateId);
                var aggregate     = (A)_eventRepo
                                    .FetchAggregateEvent(command.AggregateId) // <-- Fetch events from repo
                                    .Aggregate(initAggregate, _applyEvent);   // <-- Reduce the array of events to an AggregateRoot with the current state

                // Command handler to create new events
                var newEvents = _serviceLocator
                                .Resolve <ICommandHandler <C, A> >()
                                .Handle(command, aggregate)
                                .ToList();

                // Apply the newly created events we got from the command handler
                newEvents
                .Where(e => e is IAggregateEvent)     // Only apply Aggreage Events
                .Select(e => e as IAggregateEvent)
                .ToList()
                .ForEach(e => _applyEvent(aggregate, e));

                // Persist newly created events
                newEvents.ForEach(_eventRepo.PersistEvent);

                // Mark the command as successful
                _eventRepo.PersistEvent(new CommandFulfilledEvent(command));

                // Log
                _log.Info($"Command {command.CommandId} Succesful");
            }
            catch (Exception ex)
            {
                // Log the rejected command
                _eventRepo.PersistEvent(new CommandRejectedEvent(command, ex));
                var msg = $"Command Rejected. CommandId: {command.CommandId}. {ex.Message}";
                _log.Error(msg, ex);
                throw new CommandRejectedException(msg, ex);
            }
        }