Esempio n. 1
0
        public void Configure(IApplicationBuilder app,
                              IEventStoreBus eventBus,
                              IEventStoreProjections projections,
                              WebSocketHandler wsHandler,
                              VotingReadModelService readModelService,
                              ILogger <Startup> logger)
        {
            app.UseCors("CorsPolicy");
            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Voting API"));
            app.UseWebSockets();
            app.MapWebSocketManager("/ws", wsHandler);

            projections.CreateAsync(Projections.Voting)
            .DefaultRetryAsync()
            .Wait();

            eventBus.Subscribe(
                async(@event) =>
            {
                var snapshot = await readModelService.AddOrUpdate(@event);
                logger.LogInformation(snapshot.ToString());
                await wsHandler.SendMessageToAllAsync(snapshot);
            })
            .DefaultRetryAsync()
            .Wait();
        }
        public void Start()
        {
            var serviceProvider = _factory.CreateBuilder();

            foreach (var subscription in _registry)
            {
                foreach (var handlerType in subscription.Value)
                {
                    _logger.LogDebug($"Subscribing {handlerType} to messsage {subscription.Key}");
                    Retry(() => Subscribe(subscription.Key, handlerType));
                }
            }

            void Subscribe(Type messageType, Type messageHandlerType)
            {
                _bus.Subscribe(messageType, _subscription,
                               async(object msg) =>
                {
                    _logger.LogDebug($"Handling event type {messageType}");
                    dynamic handler = (IMessageHandler)serviceProvider.GetService(messageHandlerType);
                    await handler.Handle((dynamic)msg);
                });
            }

            void Retry(Action action, int retries = 5) =>
            Policy.Handle <Exception>()
            .WaitAndRetry(retries, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
            .Execute(action);
        }