title: Managing and Closing Dynamically created SQL connections in .net
body: <p>I have a c# windows form application that connects to databases dynamically where each user may connect to different databases.</p>
  
  <p>The current implementation is as follows:</p>
  
  <p>Connection Repository that contains a dynamically populated list of connections (per user).</p>
  
  <p>When a user initiates a request that requires a database connection the respective connection is looked up from the connection repository ,opened , and then used in the user request .</p>
  
  <p><strong>Code Sample from the connection repository</strong></p>
  
  <pre><code>public class RepoItem
  {
      public string databasename;
      public SqlConnection sqlcnn;
  }
  
  public class ConnectionRepository
  {
      private List&lt;RepoItem&gt; connectionrepositroylist;
  
      public SqlConnection getConnection(String dbname)
      {
          SqlConnection cnn = (from n in connectionrepositroylist
                               where n.databasename == dbname
                               select n.sqlcnn).Single;
  
          cnn.Open();
          return cnn;
      }
  }
  </code></pre>
  
  <p><em>sorry for any code errors i just improvised a small version of the implementation for demonstration purpose.</em></p>
  
  <p>I'am not closing connections after a command execution because it may be used by another command simultaneously.</p>
  
  <p><strong>The questions are:</strong></p>
  
  <ul>
  <li><p>Should i be worried about closing the connections ?</p></li>
  <li><p>Does connection close automatically if it is idle for a specific period ?</p></li>
  </ul>
  
  <p>I have a method in mind to implement a timer in the created Connection Repository and check for idle connections through the <code>Executing</code> <code>ConnectionState Enumeration</code> and close them manually.
  Any suggestions are welcome .</p>
  
  <p>When i want a specific connection i call the getConnection function in the ConnectionRepository class and pass the database name as a parameter.</p>
  
  <p>PS: I didn't post the complete implemented code because it is quite big and includes the preferences that affect the populating of the connection list.</p>