antonyvorontsov / RabbitMQ.Client.Core.DependencyInjection

.Net Core library-wrapper of RabbitMQ.Client for Dependency Injection.
MIT License
111 stars 36 forks source link

Allowing us to add our own Hosting Service #101

Open NO1225 opened 2 years ago

NO1225 commented 2 years ago

I have been using this library for a while, and let me say that it was a great help and time saver.

I use the hosting service to set the baseQos for the channel, with the hosted service added automatically with the AddMqServices extension method, i can only set the value for after the first batch, which could be deadly if i have a huge number of messages waiting in the queue, or when creating a new pod to help with the messages

this is an example for my hosting service, and i had to make a new custom extension for adding the mq service as a workaround

 public class MQConsumingService : IHostedService
    {
        readonly IConsumingService _consumingService;
        private readonly IConfiguration _configuration;
        readonly ILogger<MQConsumingService> _logger;

        public MQConsumingService(
            IConsumingService consumingService,
            IConfiguration configuration,
            ILogger<MQConsumingService> logger)
        {
            _consumingService = consumingService;
            _configuration = configuration;
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting consuming.");

            var rabbitMqClientOptions = _configuration.GetSection("RabbitMq").Get<MqServiceOptions>();

            _consumingService.Channel.BasicQos(rabbitMqClientOptions.PrefetchSize, rabbitMqClientOptions.PrefetchCount, rabbitMqClientOptions.Global);

            _consumingService.StartConsuming();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stopping consuming.");
            _consumingService.StopConsuming();
            return Task.CompletedTask;
        }
    }