Пример #1
0
        private static IDisposable SubscribeToReceiveMessages <THandler>(
            IEventHandlerBinder binder,
            THandler handler,
            ServiceBusSettings settings,
            Configuration configuration,
            Dictionary <Type, QueueClient> queues) where THandler : class
        {
            Type eventType = ((dynamic)binder).EventType;

            var queueName = string.Format("{0}_on_{1}.{2}",
                                          EventHandler.Name(handler),
                                          eventType.AggregateTypeForEventType().Name,
                                          eventType.EventName());

            var bus = new InProcessEventBus(errorSubject: (ISubject <EventHandlingError>)configuration.EventBus.Errors);
            var eventBusSubscription = binder.SubscribeToBus(handler, bus);

            var receive = SimulatedReceive;

            if (receive != null)
            {
                var receiveSubscription = receive.Subscribe(e => bus.PublishAsync(e).Subscribe(_ => { }, ex => bus.PublishErrorAsync(new EventHandlingError(ex, @event: e))));
                return(new CompositeDisposable(eventBusSubscription,
                                               receiveSubscription));
            }

            var queueClient = settings.CreateQueueClient(
                queueName,
                settings.ConfigureQueue);

            // starting listening on the queue for incoming events
            queueClient.OnMessage(msg =>
            {
                var storedEvent = msg.GetBody <string>()
                                  .FromJsonTo <StoredEvent>();

                var @event = Serializer.DeserializeEvent(
                    aggregateName: storedEvent.AggregateName,
                    eventName: storedEvent.EventName,
                    body: storedEvent.Body,
                    aggregateId: storedEvent.AggregateId,
                    sequenceNumber: storedEvent.SequenceNumber,
                    timestamp: storedEvent.Timestamp);

                bus.PublishAsync(@event).Subscribe(
                    _ => msg.Complete(),
                    ex => bus.PublishErrorAsync(new EventHandlingError(ex, @event: @event)));
            });

            queues[((dynamic)binder).EventType] = queueClient;

            return(new CompositeDisposable(eventBusSubscription, Disposable.Create(queueClient.Close)));
        }