Exemple #1
0
        private RabbitMQChannel GetNewChannel()
        {
            RabbitMqConnection connection = null;
            IModel             channel    = null;

            try
            {
                while (channel == null)
                {
                    connection = _connectionPool.Get();
                    channel    = connection.CreateChannel();
                    if (channel == null)                    // достигли максимального количества каналов на соединение
                    {
                        _connectionPool.Return(connection);
                    }
                }
            }
            finally
            {
                _connectionPool.Return(connection);
            }
            channel.ModelShutdown += (sender, args) =>
            {
                Console.WriteLine("The connection to rabbitMQ broker was closed");
                //_logger.Info("The connection to rabbitMQ broker was closed");
            };
            return(new RabbitMQChannel(channel, connection));
        }
Exemple #2
0
        public void SendMessage(IMessage message, MessageMetadata metadata)
        {
            try
            {
                if (!IsConnected)
                {
                    return;
                }

                byte[] body = SerializeMessage(message, metadata.SerializationType);

                using (IModel channel = RabbitMqConnection.CreateChannel(this))
                {
                    IBasicProperties basicProperties = RabbitMqConnection.CreateBasicProperties(channel, message, metadata);

                    string routingKey = string.IsNullOrEmpty(metadata.ReplyTo)
                        ? string.IsNullOrEmpty(metadata.Topic) ? message.GetType().Name : metadata.Topic
                        : metadata.ReplyTo;

                    Logger.LogInformation($"Send message to {metadata.Destination} of type {message.GetType().Name} with routing key: {routingKey}");

                    RabbitMqConnection.PublishMessage(channel, metadata.Destination, basicProperties, body, routingKey);
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Send message exception. HostName: {BrokerConfiguration.HostName} ... ");
            }
        }
Exemple #3
0
        private void ConsumerOnReceived(object sender, BasicDeliverEventArgs basicDeliverEventArgs)
        {
            if (sender is EventingBasicConsumer consumer)
            {
                consumer.Received -= ConsumerOnReceived;
            }

            if (_responseActions.TryRemove(basicDeliverEventArgs.BasicProperties.CorrelationId, out ResponseAction responseAction))
            {
                Logger.LogInformation($"Response received for message {basicDeliverEventArgs.BasicProperties.CorrelationId}");
                IMessage message;

                bool success = Enum.TryParse(basicDeliverEventArgs.BasicProperties.ContentEncoding,
                                             true,
                                             out SerializationType serializationType);

                if (success)
                {
                    message = DeserializeMessage(basicDeliverEventArgs.Body, responseAction.ExpectedResponse, serializationType);
                }
                else
                {
                    Logger.LogError($"Cannot deserialize object type { responseAction.ExpectedResponse} serialize in {basicDeliverEventArgs.BasicProperties.ContentEncoding}");
                    return;
                }
                responseAction.OnSuccess(message,
                                         RabbitMqConnection.CreateMetadata(basicDeliverEventArgs.BasicProperties,
                                                                           basicDeliverEventArgs.RoutingKey,
                                                                           Serializers[SerializationType.Binary],
                                                                           basicDeliverEventArgs.DeliveryTag));
            }
        }
Exemple #4
0
 protected override void OnConnect(object sender, EventArgs e)
 {
     using (IModel channel = RabbitMqConnection.CreateChannel(this))
     {
         RabbitMqConnection.CreateExchange(channel, MessageMetadata.RpcDestination, ExchangeType.Topic);
     }
 }
        public void ShouldConnectAndObserveConnection()
        {
            var rabbitMqConnectionOptions = new RabbitMqConnectionOptions()
            {
                HostName = "localhost",
                Password = "******",
                Username = "******",
            };


            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Debug)
                         .WriteTo.Debug()
                         .CreateLogger();

            var loggerFactory = new LoggerFactory().AddSerilog(Log.Logger);

            var anabasisAppContext = new AnabasisAppContext("appName", "appGroup", new Version(1, 0));

            var connection = new RabbitMqConnection(rabbitMqConnectionOptions, anabasisAppContext, loggerFactory);

            var rabbitMqConnectionStatusMonitor = new RabbitMqConnectionStatusMonitor(connection, loggerFactory);

            Assert.AreEqual(true, rabbitMqConnectionStatusMonitor.IsConnected);
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        private void Run()
        {
            var builder = new DbContextOptionsBuilder <OnderhoudBeheerContext>();

            builder.UseSqlServer(_dbConnectionString);
            var options = builder.Options;

            while (true)
            {
                try
                {
                    using (var rabbit = new RabbitMqConnection(_options))
                        using (var publisher = new EventPublisher(rabbit))
                            using (var service = new ApkEventService(options, publisher))
                                using (var dispatcher = new ApkDispatcher(rabbit, service))
                                {
                                    dispatcher.StartListening();
                                    while (rabbit.Channel.IsOpen)
                                    {
                                        Thread.Sleep(60000);
                                    }
                                    _service.Log(new LogMessage("Lost connection with RabbitMq"));
                                }
                }
                catch (Exception e)
                {
                    _service.LogException(new LogMessage(e.Message, e.StackTrace));
                    Thread.Sleep(5000);
                }
            }
        }
Exemple #7
0
        public void Test()
        {
            var option = new BusOptions()
            {
                ExchangeName = "Unit Test",
                HostName     = "localhost",
                Port         = 7000,
                QueueName    = "TestQueue"
            };
            var flag = new AutoResetEvent(false);

            using (var connection = new RabbitMqConnection(option))
                using (var publisher = new EventPublisher(connection))
                    using (var dis = new DispatcherMock(connection, flag))
                    {
                        dis.StartListening();
                        publisher.Publish(new TestEvent()
                        {
                            CorrelationID = new Guid(),
                            RoutingKey    = "Test",
                            TimeStamp     = DateTime.Now,
                            TestString    = "Hello, World!"
                        });
                        flag.WaitOne();
                        Assert.IsTrue(dis.Handled);
                        Assert.AreEqual("Hello, World!", dis.Event.TestString);
                    }
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            var busoption = BusOptions.CreateFromEnvironment();
            var builder   = new DbContextOptionsBuilder <AuditContext>();

            builder.UseSqlServer(Environment.GetEnvironmentVariable("dbconnectionstring"));
            var options    = builder.Options;
            var eventRepo  = new EventRepository(options);
            var logService = new LogService(new DirectoryInfo(Path.Combine(Environment.GetEnvironmentVariable("logpath"), "RabbitMqLog")));

            while (true)
            {
                try
                {
                    using (var rabbit = new RabbitMqConnection(busoption))
                        using (var logger = new AuditLogger(eventRepo, rabbit, logService))
                        {
                            while (rabbit.Channel.IsOpen)
                            {
                                Thread.Sleep(60000);
                            }
                            logService.Log(new LogMessage("Lost connection with RabbitMq"));
                        }
                }
                catch (Exception e)
                {
                    logService.LogException(new LogMessage(e.Message, e.StackTrace));
                    Thread.Sleep(5000);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        private void Run()
        {
            var builder = new DbContextOptionsBuilder <GarageAdministratieContext>();

            builder.UseSqlServer(_dbConnectionString);
            var options = builder.Options;

            while (true)
            {
                try
                {
                    using (var rabbit = new RabbitMqConnection(_options))
                        using (var dispatcher = new OnderhoudOpdrachtenDispatcher(rabbit, options))
                        {
                            dispatcher.StartListening();
                            while (rabbit.Channel.IsOpen)
                            {
                                Thread.Sleep(60000);
                            }
                            _service.Log(new LogMessage("Lost connection with RabbitMq"));
                        }
                }
                catch (Exception e)
                {
                    _service.LogException(new LogMessage(e.Message, e.StackTrace));
                    Thread.Sleep(5000);
                }
            }
        }
Exemple #10
0
        //private readonly string HostName = "localhost";
        //private readonly int Port = 5672;
        //private readonly string UserName = "******";
        //private readonly string Password = "******";
        //private readonly string QueueName = "QueueName";



        public RabbitMqChannelReceivedServer(ILogManager logger, IConfigProvider configProvider, ICommandHandleFactory handleFactory)
        {
            _logger               = logger;
            _rabbitMqConnection   = configProvider?.GetRabbitMqConnection();
            _commandHandleFactory = handleFactory;
            _semaphore            = new SemaphoreSlim(_rabbitMqConnection.MaxExecutingCommands);//并发数
            _logger.Info($"{nameof(RabbitMqChannelReceivedServer)} init");
        }
Exemple #11
0
        protected override void OnConnect(object sender, EventArgs e)
        {
            if (RabbitMqConnection.RegisteredConnectors.ContainsKey(Id))
            {
                return;
            }
            IModel channel = RabbitMqConnection.CreateChannel(this);

            RabbitMqConnection.ConfigureChannel(channel, BrokerConfiguration.ChannelConfiguration);
            _eventingBasicConsumer           = RabbitMqConnection.CreateEventingBasicConsumer(channel);
            _eventingBasicConsumer.Received += EventingBasicConsumerOnReceived;

            foreach (BrokerSubscriberConfiguration config in BrokerConfiguration.BrokerSubscriberConfiguration)
            {
                RabbitMqConnection.CreateExchange(channel, config.ExchangeName, config.ExchangeType);

                config.QueueName = RabbitMqConnection.CreateQueue(channel,
                                                                  config.QueueName,
                                                                  config.Exclusive,
                                                                  config.Durable,
                                                                  config.AutoDelete);

                switch (config.ExchangeType)
                {
                case ExchangeType.Topic:
                case ExchangeType.Direct:
                    if (config.Topic != null)
                    {
                        foreach (string topic in config.Topic)
                        {
                            RabbitMqConnection.CreateBinding(channel, config.QueueName, config.ExchangeName, topic);
                        }
                    }
                    else
                    {
                        foreach (KeyValuePair <Type, List <Action <object, MessageMetadata> > > obj in _registerMethodDictionary)
                        {
                            if (!obj.Key.IsGenericType)
                            {
                                RabbitMqConnection.CreateBinding(channel, config.QueueName, config.ExchangeName, obj.Key.Name);
                            }
                        }
                    }
                    break;

                case ExchangeType.Fanout:
                    RabbitMqConnection.CreateBinding(channel, config.QueueName, config.ExchangeName);
                    break;
                }

                RabbitMqConnection.ConsumeQueue(this,
                                                channel,
                                                config.QueueName,
                                                Id.ToString(),
                                                true,
                                                _eventingBasicConsumer);
            }
        }
Exemple #12
0
        static void Main(string[] args)
        {
            RabbitMqConnection rmqConnection = new RabbitMqConnection();
            Person             person        = new Person()
            {
                Id = 304011601, Name = "Mehmed Fatih", SurName = "Temiz", BirthDate = new DateTime(1988, 10, 25), Message = "Nesne Takip Projesi Tam Gaz devam Ediyor", MessageSendTime = DateTime.Now
            };

            rmqConnection.SendMessageToQuery(JsonConvert.SerializeObject(person), "fatihinAnahtari", "fatihinAnahtari");
        }
Exemple #13
0
 public static Task SendMessageAsync(this RabbitMqConnection connection, string exchangeName, string routeKey, byte[] message)
 {
     return(Task.Run(() =>
     {
         var channel = connection.Rent();
         if (!channel.SendMessage(exchangeName, routeKey, message))
         {
             connection.Logger.LogError("send message failed");
         }
         connection.Return(channel);
     }));
 }
Exemple #14
0
        public virtual void Connect()
        {
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), RabbitMqConfig);

            if (File.Exists(filePath))
            {
                BrokerConfiguration = Serializers[SerializationType.Json].FileToObject <BrokerConfiguration>(filePath);
            }

            RabbitMqConnection.OnConnect += OnConnect;
            RabbitMqConnection.Connect(BrokerConfiguration);
        }
        public void Dispose_SwallowsExceptions()
        {
            var connection = Substitute.For<IConnection>();
            var factory = Substitute.For<IConnectionFactory>();
            factory.CreateConnection().Returns(connection);
            connection.When(x => x.Dispose()).Throw(new ChannelAllocationException());

            var sut = new RabbitMqConnection(factory);
            sut.CreateModel();

            //Act & Assert
            Assert.DoesNotThrow(() => sut.Dispose());
        }
 private void CloseConnection(RabbitMqConnection connection)
 {
     try
     {
         connection.BrokerConnection.Close();
         connection.BrokerConnection.Dispose();
     }
     catch (IOException) { }
     catch (Exception ex)
     {
         Console.WriteLine("RabbitMQ connection closure failed", ex);
     }
 }
Exemple #17
0
        public Task <Tuple <TResponse, MessageMetadata, string> > RequestAsync <TResponse>(IMessage message, MessageMetadata metadata)
            where TResponse : class, IMessage
        {
            string queueName = null;

            try
            {
                var    taskCompletionSource = new TaskCompletionSource <Tuple <TResponse, MessageMetadata, string> >();
                string routingKey           = string.IsNullOrEmpty(metadata.ReplyTo)
                    ? string.IsNullOrEmpty(metadata.Topic) ? message.GetType().Name : metadata.Topic
                    : metadata.ReplyTo;

                IModel channel = RabbitMqConnection.CreateChannel(this);
                queueName = RabbitMqConnection.CreateQueue(channel, string.Empty, true, false, false);

                metadata.MessageId = string.IsNullOrEmpty(metadata.ReplyTo) ? queueName : metadata.ReplyTo;
                metadata.ReplyTo   = queueName;

                RabbitMqConnection.CreateBinding(channel, queueName, MessageMetadata.RpcDestination, metadata.ReplyTo);
                EventingBasicConsumer consumer = RabbitMqConnection.CreateEventingBasicConsumer(channel);

                consumer.Received += ConsumerOnReceived;
                RabbitMqConnection.ConsumeQueue(this, channel, queueName, string.Empty, true, consumer);

                IBasicProperties basicProperties = RabbitMqConnection.CreateBasicProperties(channel, message, metadata);
                basicProperties.ReplyTo = string.IsNullOrEmpty(metadata.ReplyTo) ? queueName : metadata.ReplyTo;

                if (!basicProperties.IsHeadersPresent())
                {
                    basicProperties.Headers = new Dictionary <string, object>();
                }
                basicProperties.Headers[MessageMetadata.ResponseDestinationHeaderKey] = MessageMetadata.RpcDestination;
                RegisterResponseAction(basicProperties.CorrelationId, queueName, consumer, typeof(TResponse), taskCompletionSource);

                byte[] body = SerializeMessage(message, metadata.SerializationType);

                Logger.LogInformation(
                    $"Send request to: {metadata.Destination} with routingkey: {routingKey} - ReplyTo: {basicProperties.ReplyTo} of type: {typeof(TResponse).Name} id: {basicProperties.CorrelationId}");
                RabbitMqConnection.PublishMessage(channel, metadata.Destination, basicProperties, body, routingKey);
                return(taskCompletionSource.Task);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"{nameof(RequestAsync)}");
                if (queueName != null)
                {
                    ForgetMessage(queueName);
                }
                throw;
            }
        }
        public void AnyMethodCall_CreatesConnection()
        {
            var connection = Substitute.For<IConnection>();
            var factory = Substitute.For<IConnectionFactory>();
            factory.CreateConnection().Returns(connection);

            var sut = new RabbitMqConnection(factory);

            //Act
            sut.CreateModel();

            //Assert
            factory.Received().CreateConnection();
        }
        public void Dispose_DisposesConnection()
        {
            var connection = Substitute.For<IConnection>();
            var factory = Substitute.For<IConnectionFactory>();
            factory.CreateConnection().Returns(connection);

            var sut = new RabbitMqConnection(factory);

            //Act
            sut.CreateModel();
            sut.Dispose();

            //Assert
            connection.Received().Dispose();
        }
        public static void AddMessagePublishing(this IServiceCollection services, string queueName, Action <MessagingBuilder> builderFn = null)
        {
            var builder = new MessagingBuilder(services);

            services.AddHostedService <QueueReaderService>();
            services.AddSingleton(new MessageHandlerRepository(builder.MessageHandlers));

            builderFn?.Invoke(builder);
            var queueNameService = new QueueName(queueName);

            services.AddSingleton(queueNameService);
            var connection = new RabbitMqConnection();

            services.AddSingleton(connection);
            services.AddScoped <IMessagePublisher, RabbitMqMessagePublisher>();
        }
Exemple #21
0
        private void EventingBasicConsumerOnReceived(object sender, BasicDeliverEventArgs args)
        {
            try
            {
                string typeString = args.BasicProperties.Type;

                Type type = null;
                if (!string.IsNullOrWhiteSpace(typeString))
                {
                    type = Type.GetType(typeString, false);
                }

                if (type == null)
                {
                    throw new TypeLoadException($"Unknown type {typeString}. Failed to properly consume message.");
                }

                IMessage message;

                bool success = Enum.TryParse(args.BasicProperties.ContentEncoding,
                                             true,
                                             out SerializationType serializationType);
                if (success)
                {
                    message = DeserializeMessage(args.Body, type, serializationType);
                }
                else
                {
                    Logger.LogError(
                        $"Cannot deserialize object type {type.Name} serialize in {args.BasicProperties.ContentEncoding}");
                    return;
                }

                foreach (var call in _registerMethodDictionary[type])
                {
                    Task.Factory.StartNew(() => call(message,
                                                     RabbitMqConnection.CreateMetadata(args.BasicProperties,
                                                                                       args.RoutingKey,
                                                                                       Serializers[SerializationType.Binary],
                                                                                       args.DeliveryTag)));
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Message reception error for {args.BasicProperties.Type}");
            }
        }
        public void Return(RabbitMqConnection connection, bool forceClose = false)
        {
            if (connection == null)
            {
                return;
            }

            if (forceClose || connection.IsNoChannels || !connection.BrokerConnection.IsOpen)
            {
                CloseConnection(connection);
                return;
            }

            if (connection.BrokerConnection.IsOpen)
            {
                _connections.Add(connection);
            }
        }
        /// <summary>
        /// 注册健康监测组件
        /// </summary>
        public virtual void AddHealthChecks()
        {
            var redisString = _redisConfig.dbconfig.ConnectionStrings[0].Replace(",prefix=", string.Empty).Replace(",poolsize=50", string.Empty);

            _services.AddHealthChecks()
            .AddProcessAllocatedMemoryHealthCheck(maximumMegabytesAllocated: 200, tags: new[] { "memory" })
            //.AddProcessHealthCheck("ProcessName", p => p.Length > 0) // check if process is running
            .AddMySql(_mysqlConfig.WriteDbConnectionString)
            .AddMongoDb(_mongoConfig.ConnectionStrings)
            .AddRabbitMQ(x =>
            {
                return
                (RabbitMqConnection.GetInstance(x.GetService <IOptionsSnapshot <RabbitMqConfig> >()
                                                , x.GetService <ILogger <dynamic> >()
                                                ).Connection);
            })
            //.AddUrlGroup(new Uri("https://localhost:5001/weatherforecast"), "index endpoint")
            .AddRedis(redisString);
        }
        //private readonly ILogManager _logManager;

        public RabbitMqHelper(IConfigProvider configProvider)
        {
            _rabbitMqConnection = configProvider.GetRabbitMqConnection();

            //创建连接工厂
            var connectionFactory = new ConnectionFactory //创建连接工厂对象
            {
                HostName = _rabbitMqConnection.HostName,  //IP地址
                Port     = _rabbitMqConnection.Port,      //端口号
                UserName = _rabbitMqConnection.UserName,  //用户账号
                Password = _rabbitMqConnection.Password   //用户密码
            };

            //创建连接
            _connection = connectionFactory.CreateConnection();
            //创建通道
            _channel = _connection.CreateModel();
            //声明交换机
            _channel.ExchangeDeclare(_rabbitMqConnection.ExchangeName, ExchangeType.Topic);
        }
    public static IServiceCollection AddAdncInfraRabbitMq(this IServiceCollection services, IConfigurationSection rabitmqSection)
    {
        if (services.HasRegistered(nameof(AddAdncInfraRabbitMq)))
        {
            return(services);
        }

        return(services
               .Configure <RabbitMqConfig>(rabitmqSection)
               .AddSingleton <IRabbitMqConnection>(provider =>
        {
            var options = provider.GetRequiredService <IOptions <RabbitMqConfig> >();
            var logger = provider.GetRequiredService <ILogger <RabbitMqConnection> >();
            var serviceInfo = services.GetServiceInfo();
            var clientProvidedName = serviceInfo?.Id ?? "unkonow";
            return RabbitMqConnection.GetInstance(options, clientProvidedName, logger);
        })
               .AddSingleton <RabbitMqProducer>()
               );
    }
Exemple #26
0
        public void SendMessage(byte[] body, IMessage message, MessageMetadata metadata)
        {
            if (!IsConnected)
            {
                return;
            }

            using (IModel channel = RabbitMqConnection.CreateChannel(this))
            {
                IBasicProperties basicProperties = RabbitMqConnection.CreateBasicProperties(channel, message, metadata);

                string routingKey = string.IsNullOrEmpty(metadata.ReplyTo)
                    ? string.IsNullOrEmpty(metadata.Topic) ? message.GetType().Name : metadata.Topic
                    : metadata.ReplyTo;

                Logger.LogInformation($"Send message to {metadata.Destination} of type {message.GetType().Name} with routing key: {routingKey}");

                RabbitMqConnection.PublishMessage(channel, metadata.Destination, basicProperties, body, routingKey);
            }
        }
        /// <summary>
        /// 注册健康监测组件
        /// </summary>
        public virtual void AddHealthChecks()
        {
            var mysqlConfig = _configuration.GetMysqlSection().Get <MysqlConfig>();
            var mongoConfig = _configuration.GetMongoDbSection().Get <MongoConfig>();
            var redisConfig = _configuration.GetRedisSection().Get <RedisConfig>();

            _services.AddHealthChecks()
            //.AddProcessAllocatedMemoryHealthCheck(maximumMegabytesAllocated: 200, tags: new[] { "memory" })
            //.AddProcessHealthCheck("ProcessName", p => p.Length > 0) // check if process is running
            .AddMySql(mysqlConfig.ConnectionString)
            .AddMongoDb(mongoConfig.ConnectionString)
            .AddRabbitMQ(x =>
            {
                return
                (RabbitMqConnection.GetInstance(x.GetService <IOptionsSnapshot <RabbitMqConfig> >()
                                                , x.GetService <ILogger <dynamic> >()
                                                ).Connection);
            })
            //.AddUrlGroup(new Uri("https://localhost:5001/weatherforecast"), "index endpoint")
            .AddRedis(redisConfig.dbconfig.ConnectionString);
        }
 public RabbitMqChannelWriteClient(ILogManager logManager, IConfigProvider configProvider)
 {
     _logManager         = logManager;
     _rabbitMqConnection = configProvider.GetRabbitMqConnection();
 }
Exemple #29
0
        static void Main(string[] args)
        {
            RabbitMqConnection rmqConnection = new RabbitMqConnection();

            rmqConnection.ReceiveMessageFromQuery("fatihinAnahtari");
        }
Exemple #30
0
        public static IServiceCollection AddOptionsAndHealthChecks(this IServiceCollection services, IConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var sql = new SqlServerConnection();

            configuration.Bind("Infra:Connections:Sql", sql);
            services.Configure <SqlServerConnection>(instance => configuration.Bind("Infra:Connections:Sql", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <SqlServerConnection> >().Value);

            var mongodb = new MongoDbConnection();

            configuration.Bind("Infra:Connections:Mongodb", mongodb);
            services.Configure <MongoDbConnection>(instance => configuration.Bind("Infra:Connections:Mongodb", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <MongoDbConnection> >().Value);

            var rabbit = new RabbitMqConnection();

            configuration.Bind("Infra:Connections:RabbitMQ", rabbit);
            services.Configure <RabbitMqConnection>(instance => configuration.Bind("Infra:Connections:RabbitMQ", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <RabbitMqConnection> >().Value);

            var redis = new RedisCacheOptions();

            configuration.Bind("Infra:Connections:Redis", redis);
            services.Configure <RedisCacheOptions>(instance => configuration.Bind("Infra:Connections:Redis", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <RedisCacheOptions> >().Value);

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = redis.Configuration;
                options.InstanceName  = redis.InstanceName;
            });

            services.AddMassTransitHostedService();
            services.TryAddSingleton(KebabCaseEndpointNameFormatter.Instance);
            services.AddMassTransit(cfg =>
            {
                cfg.SetKebabCaseEndpointNameFormatter();
                cfg.AddBus(factory => Bus.Factory.CreateUsingRabbitMq(x =>
                {
                    x.UseHealthCheck(factory);

                    x.Host(rabbit.Host, rabbit.VirtualHost);
                    x.ConfigureEndpoints(factory);
                }));
            });

            services.AddHealthChecks()
            .AddCheck("api", _ => HealthCheckResult.Healthy())
            .AddRedis(redis.Configuration, "redis")
            .AddMongoDb(mongodb.ConnectionString, mongodb.Collection, "mongodb")
            .AddSqlServer(sql.ConnectionString)
            .AddRabbitMQ(rabbit.ConnectionUri, new SslOption(), "rabbitmq");



            services.AddWrapperizer().AddOutboxServices(options =>
            {
                options.UseSqlServer(sql.ConnectionString,
                                     sqlOptions =>
                {
                    // sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);

                    sqlOptions.MigrationsHistoryTable("__OutboxMigrationHistory", OutboxEventContext.DefaultSchema);

                    //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    sqlOptions.EnableRetryOnFailure(15, TimeSpan.FromSeconds(30), null);
                });
            });

            return(services);
        }