mercredi 27 février 2019

Wrap RabbitMQ Connection in a singleton class

I have read that when I use RabbitMQ the best practice is to use one connection per process, so I would like to create a singleton class for the rabbitmq connection. I would like to use the Lazy version of Singleton from: Implementing the Singleton Pattern in C#

I write this class:

public class RabbitConnection
{
    private static readonly Lazy<RabbitConnection>  Lazy = new Lazy<RabbitConnection>(() => new RabbitConnection());

    private RabbitConnection()
    {
        IConnectionFactory connectionFactory = new ConnectionFactory
        {
            HostName = "127.0.0.1",
            Port = 5672,
            UserName = "Username",
            Password = "********"
        };

        Connection = connectionFactory.CreateConnection();
    }

    public static RabbitConnection Instance
    {
        get { return Lazy.Value; }
    }

    public IConnection Connection { get; }
}

And use this like:

var channel = RabbitConnection.Instance.Connection.CreateModel();
channel.QueueDeclare("myQueue", true, false, false, null);
....

Is this implementation right or wrong? Thank you

Aucun commentaire:

Enregistrer un commentaire