title: Connecting to RabbitMQ, method level best practices?
body: <p>I have a class that reads and writes messages using rabbitmq. I don't want to have connection related info in this class's constructor nor inside the read and write methods. Instead, I want to make a connection when I use the write and read methods. What is the best way/practice to go about tackling this issue?</p>
  
  <p>//Edit 1</p>
  
  <pre><code>public class Rabbit : IMessageBus
  {   
      // Implementation of methods for Rabbit class go here
      private List&lt;string&gt; publishQ = new List&lt;string&gt;();
      private List&lt;string&gt; subscribeQ = new List&lt;string&gt;();
  
      ConnectionFactory factory = null;
      IConnection connection = null;
      IModel channel = null;  
      QueueingBasicConsumer consumer = null;  
  
  
      public void write ( Measurement m1 )
      {
          byte[] body = Measurement.AltSerialize( m1 );
  
          foreach (string queue in publishQ) 
          {
              channel.BasicPublish("", queue, null, body);
              Console.WriteLine("\n  [x] Sent to queue {0}.", queue);
          }
      }
  
      public void publish(string queueName)
      {   
          channel.QueueDeclare(queueName, true, false, false, null); //durable=true
  
          publishQ.Add(queueName); //and, add it the list of queue names to publish to
      }
  
      public Measurement read() 
      {       
          foreach (string queue in subscribeQ) 
          {
              channel.BasicConsume(queue, true, consumer);
          }
  
          System.Console.WriteLine(" [*] Waiting for messages." +
                                  "To exit press CTRL+C");
          BasicDeliverEventArgs ea = 
              (BasicDeliverEventArgs)consumer.Queue.Dequeue();
  
          return Measurement.AltDeSerialize(ea.Body);
      }
  
      public void subscribe(string queueName)
      {
          channel.QueueDeclare(queueName, true, false, false, null);
          subscribeQ.Add(queueName);
      }
  
      public static string MsgSysName;
      public string MsgSys
      {
          get 
          { 
              return MsgSysName;
          }
          set
          {
              MsgSysName = value;
          }
      }
  
      public Rabbit(string _msgSys) //Constructor
      {   
          factory = new ConnectionFactory();
          factory.HostName = "localhost"; 
          connection = factory.CreateConnection();
          channel = connection.CreateModel();
          consumer = new QueueingBasicConsumer(channel);
  
          System.Console.WriteLine("\nMsgSys: RabbitMQ");
          MsgSys = _msgSys;
      }
  
      ~Rabbit()
      {
          //
      }   
  }
  </code></pre>