Search code examples
rabbitmqautofacrebus

Configure multiple instances of rebus for a single process with autofac


I ran into a situation where my application need to send messages to 2 queues that are in two different virtual hosts in rabbit and read from one of them. Moving those 2 queues into one virtual host (which is the perfect solution) not possible. Therefore, I need to run 2 rebus instances in a single process.

I'm using autofac for dependency injection. Could you please redirect me to some resource explaining how I can setup multiple instances in rebus with autofac in a single process?

thank you very much!


Solution

  • You should configure the bus instance, that you intend to use to send/publish messages on the other vhost, as a one-way client, which you then access through a dedicated service you create for this purpose.

    Something along the lines of this:

    public class OtherVhostBusClient : IDisposable
    {
        readonly IBus _bus;
    
        public OtherVhostBusClient(string amqpConnectionString)
        {
            _bus = Configure.With(new BuiltinHandlerActivator())
                .Transport(t => {
                    t.UseRabbitMqAsOneWayClient(amqpConnectionString);
                })
                .Start();
        }
    
        public Task Publish(object e) => _bus.Publish(e);
    
        public void Dispose() => _bus.Dispose();
    }
    

    If you then configure OtherVhostBusClient as a singleton in your Autofac container, you can have it injected and use it to publish stuff on the other vhost.

    This way, you are essentially treating this as a "foreign network" of sorts, implementing the integration with it as you would any other type of integration between "networks" (could be Rebus on any other transport, HTTP, etc.)

    I hope that makes sense :)