RabbitMQ: Injecting the connection factory

The RabbitMQ C# client is a low-level pureish AMQP implementation, you'd probably want to wrap it in some higher level abstraction and then register that with your IoC container.

EasyNetQ, a higher level abstraction over the basic client, implements a persistent AMQP connection that reconnects after a connection is lost (either through network problems, or a server bounce), and rebuilds all the current subscriptions. You're welcome to take any of that code that you find useful.

In short, it's a question of wrapping connection management in some kind of PersistentConnection class, and then registering each subscription with some code to rebuild them after a successful reconnect.

I've written a blog post on wiring up EasyNetQ, the Windsor IoC container and TopShelf. I've used this technique successfully for building RabbitMQ based windows services.


The tricky part is it looks like according to the documentation ConnectionFactory doesn't implement any interfaces.

So you're really left with implementing your own, something like,

public interface IConnectionFactory
{
    ConnectionFactory Get();
    ConnectionFactory Get(string uri);
}

public class ConnectionFactoryCreator : IConnectionFactory
{
    public ConnectionFactory Get(
        string uri = "amqp://user:pass@hostName:port/vhost")
    {
        return new ConnectionFactory
        {
            Uri = uri
        };
    }
}

For the class where you end up using it,

public class RabbitMQUserClass
{
    public ConnectionFactory ConnectionFactory {get; private set;}
    public RabbitMQUserClass(IConnectionFactory connectionFactory)
    {
        ConnectionFactory = connectionFactory.Get();
    }
}