title: How to fix SQL connection leaks in this code?
body: <p>I am getting this error on my website:</p>
  
  <blockquote>
    <p>Timeout expired.  The timeout period elapsed prior to obtaining a
    connection from the pool.  This may have occurred because all pooled
    connections were in use and max pool size was reached.</p>
    
    <p>Description: An unhandled exception occurred during the execution of
    the current web request. Please review the stack trace for more
    information about the error and where it originated in the code. </p>
    
    <p>Exception Details: System.InvalidOperationException: Timeout expired. 
    The timeout period elapsed prior to obtaining a connection from the
    pool.  This may have occurred because all pooled connections were in
    use and max pool size was reached.</p>
  </blockquote>
  
  <p>This is the C# class that is being reused everywhere (I think the leak is here):</p>
  
  <pre><code>public class Generator
  {
  
  SqlConnection cn = null; // new SqlConnection(connectionString);
  
      public SqlConnection Connection {
          get {
              if (cn == null) {
              cn = new SqlConnection("Server=xxxxx,1433;Database=xxxxx;User ID=xxxxx;Password=xxxxx;Trusted_Connection=False;Encrypt=True;");
              }
              if(cn.State != ConnectionState.Open)
                  cn.Open();
  
              return cn;
          }
      }
  
  }
  </code></pre>
  
  <p>Then in my methods I use it like this:</p>
  
  <pre><code>        var cmd = _generator.Connection.CreateCommand();
          cmd.CommandText = "SELECT * FROM SomeTable";
          var reader = cmd.ExecuteReader();
  
          while (reader.Read())
          {
              //DO SOMETHING
          }
          reader.Close();
  </code></pre>
  
  <p><strong>EDIT:</strong> In the class of my methods I attempt to share the same SQL connection across multiple methods like this:</p>
  
  <pre><code>private Generator _generator;
  
  public HomeController()
  {
      InitializeConnection();
  }
  
  private void InitializeConnection()
  {
      _generator = new Generator();
  }
  </code></pre>
  
  <p>Can anyone see how I can fix the leak or what is causing my max pool issue?</p>