Search code examples
c#rabbitmqservicebusmasstransit

MassTransit and RabbitMQ, make queue survive restart when using DI


I'm trying to force the RabbitMQ queues to survive the Rabbit service restart, while forcing them to reuse the same name after the service restart is completed.

We are using our DI container to pass the message consumers

return new List<Type>
{
    typeof(Consumer1), typeof(Consumer2), typeof(Consumer3), typeof(Consumer4)
};

That collection is then passed to the configuration via

t => _kernel.Get(t));

And then registering them this way

cfg.ReceiveEndpoint(host, e =>
{
    foreach (var type in consumerTypes)
    {
        e.Consumer(type, getConsumer);
    }
});

This makes the queue to be recreated at every restart, with a GUID in the name.

If we try to do this:

cfg.ReceiveEndpoint(host, e =>
{
    foreach (var type in consumerTypes)
    {
        e.Consumer(type, getConsumer);
        e.Durable = true;
        e.AutoDelete = false;
    }
});

Then the queue is durable, but is not created upon service restart.

How can we specify a queue name for each consumer?


Solution

  • Solved doing this:

    foreach (var type in consumerTypes)
    {
        var consumerType = type;
        var queueName = string.Format("{0}_{1}",
            Environment.MachineName, consumerType.ToString());
        cfg.ReceiveEndpoint(host, queueName,
            e =>
            {
                e.Consumer(consumerType, getConsumer);
            });
    }