Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <RabbitOptions>(Configuration.GetSection("RabbitMq"));
            var rabbitOptions = Configuration.GetSection("RabbitMq").Get <RabbitOptions>();

            services.AddSingleton <IQueueProvider, RabbitMqProvider>(provider =>
            {
                var credentials = new MqCredentials(rabbitOptions.Credentials.HostName, rabbitOptions.Credentials.UserName,
                                                    rabbitOptions.Credentials.Password, rabbitOptions.QueueName);

                var rabbitProvider = new RabbitMqProvider(credentials, rabbitOptions.QueueName);
                rabbitProvider.Bind();

                //rabbitProvider.Subscribe(ReceiveMessage.GetMes);

                return(rabbitProvider);
            });
            services.AddSingleton <IRabbitService>(new RabbitService(p =>
            {
                p.Credentials = rabbitOptions.Credentials;
                p.AutoDelete  = rabbitOptions.AutoDelete;
                p.QueueName   = rabbitOptions.QueueName;
            }));



            services.AddControllers();
        }
        public RabbitService(Action <RabbitOptions> settings)
        {
            _settings = new RabbitOptions();
            settings.Invoke(_settings);

            new ConnectionFactory
            {
                HostName = _settings.Credentials.HostName,
                UserName = _settings.Credentials.UserName,
                Password = _settings.Credentials.Password
            }.CreateConnection().CreateModel().QueueDeclare(queue: _settings.QueueName, durable: false, exclusive: false, autoDelete: _settings.AutoDelete, arguments: null);

            _rabbitProvider = new RabbitMqProvider(
                new MqCredentials(
                    _settings.Credentials.HostName,
                    _settings.Credentials.UserName,
                    _settings.Credentials.Password,
                    _settings.QueueName),
                _settings.QueueName);
            _rabbitProvider.Bind();
        }