Liran Friedman
Liran Friedman

Reputation: 4287

Consumer "received" event not firing

I'm trying to set up a subscription to a RabbitMQ queue and pass it a custom event handler. So I have a class called RabbitMQClient which contains the following method:

public void Subscribe(string queueName, EventHandler<BasicDeliverEventArgs> receivedHandler)
{
    using (var connection = factory.CreateConnection())
    {
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(
                queue: queueName,
                durable: false,
                exclusive: false,
                autoDelete: false,
                arguments: null
            );

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += receivedHandler;

            channel.BasicConsume(
                queue: queueName,
                autoAck: false,
                consumer: consumer
            );
        }
    }
}

I'm using dependency injection, so I have a RabbitMQClient (singleton) interface for it.

In my consuming class, I have this method which I want to act as the EventHandler

public void Consumer_Received(object sender, BasicDeliverEventArgs e)
{
    var message = e.Body.FromByteArray<ProgressQueueMessage>();
}

And I'm trying to subscribe to the queue like this:

rabbitMQClient.Subscribe(Consts.RabbitMQ.ProgressQueue, Consumer_Received);

I can see that the queue starts to get messages, but the Consumer_Received method is not firing.

What am I missing here?

Upvotes: 10

Views: 7851

Answers (1)

vhr
vhr

Reputation: 1664

"Using" calls dispose on your connection and your event wont be triggered. Just remove your "using" block from the code so that it doesn't close the connection.

var connection = factory.CreateConnection();

var channel = connection.CreateModel();

channel.QueueDeclare(
    queue: queueName,
    durable: false,
    exclusive: false,
    autoDelete: false,
    arguments: null);

var consumer = new EventingBasicConsumer(channel);

consumer.Received += receivedHandler;

channel.BasicConsume(
    queue: queueName,
    autoAck: false,
    consumer: consumer);

Upvotes: 25

Related Questions