Exemple #1
0
        public static IServiceCollection AddBus(this IServiceCollection services, Action <BusOptions> configure = null)
        {
            var busOptions = new BusOptions();

            if (configure != null)
            {
                configure.Invoke(busOptions);
            }
            services.AddSingleton(busOptions);

            var serviceProvider = services.BuildServiceProvider();
            var configuration   = serviceProvider.GetRequiredService <IConfiguration>();

            var rabbitUrl = serviceProvider.GetRequiredService <IConfiguration>().GetConnectionString("RabbitMQ");

            if (!busOptions.Token.IsValid)
            {
                configuration.GetSection(JwtTokenParameters.ConfigurationSection).Bind(busOptions.Token);
            }


            if (string.IsNullOrEmpty(rabbitUrl))
            {
                throw new BusException("Connection string named 'RabbitMQ' is required.");
            }

            ConnectionFactory factory = new ConnectionFactory
            {
                Uri = new Uri(rabbitUrl),
            };

            var envName = serviceProvider.GetRequiredService <IHostEnvironment>().EnvironmentName;

            using (var conn = factory.CreateConnection())
                using (var model = conn.CreateModel())
                {
                    model.ExchangeDeclare($"{envName}".ToLower(), ExchangeType.Direct, true);

                    var deadletter = $"{envName}.deadletter".ToLower();
                    model.ExchangeDeclare(deadletter, ExchangeType.Fanout, true);
                    model.QueueDeclare(deadletter, true, false, false);
                    model.QueueBind(deadletter, deadletter, string.Empty);

                    model.Close();
                    conn.Close();
                }

            return(services);
        }