title: Auto-closing TIBCO EMS connections when no longer needed
body: <p>We're using TIBCO EMS from our ASP.NET 3.5 app for one interface to an external system, and it appears to be working just fine - except that the guys running the other side tells us we're racking up connections like crazy and never closing them....</p>
  
  <p>What I'm doing is routing all TIBCO traffic through a single class with static member variables for both the TIBCO <code>ConnectionFactory</code> and the <code>Connection</code> itself, having been told that constructing them is pretty resource- and time-intensive:</p>
  
  <pre><code>private static ConnectionFactory Factory
  {
      get
      {
          if (HttpContext.Current.Application["EMSConnectionFactory"] == null)
          {
             ConnectionFactory connectionFactory = CreateTibcoFactory();
             HttpContext.Current.Application["EMSConnectionFactory"] = connectionFactory;
          }
  
          return HttpContext.Current.Application["EMSConnectionFactory"] as ConnectionFactory;
      }
  }
  
  private static Connection EMSConnection
  {
      get
      {
          if (HttpContext.Current.Application["EMSConnection"] == null)
          {
             Connection connection = Factory.CreateConnection(*username*,  *password*);
             connection.ExceptionHandler += new EMSExceptionHandler(TibcoConnectionExceptionHandler);
             connection.Start();
             HttpContext.Current.Application["EMSConnection"] = connection;
          }
  
          return HttpContext.Current.Application["EMSConnection"] as Connection;
       }
   }
  </code></pre>
  
  <p>Now my trouble is: where and how could I</p>
  
  <ul>
  <li>tell the TIBCO connection to "auto-close" when no longer needed (like with the <code>SqlConnection</code>)</li>
  <li>close the TIBCO connection on an error</li>
  <li>close the TIBCO connection before our ASP.NET app finishes (or the user logs off)</li>
  </ul>
  
  <p>I don't really seem to find much useful information on how to use TIBCO EMS from the C# / .NET world...... any takers?? Thanks!!</p>