title: ASP.net best practise - where do I connect to database from?
body: <pre><code>cn = new SqlConnection(
           ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString());
  cn.Open();
  </code></pre>
  
  <p>Where should this code go assuming I have content pages and master pages?</p>
  
  <p>Should I put it in the master pages <code>Page_Init</code>?  Will it then be fully accessible from every stage of execution on my content pages?</p>
  
  <p>I'm used to classic ASP, so I would usually do it:</p>
  
  <pre><code>Declare variables
  
  Open connection
  
  process code
  
  Close connection
  
  Render HTML
  </code></pre>
  
  <p>But there are lots of stages of the page lifecycle in .net so I am wondering where it is best to place this code?</p>
  
  <p>And does this connection need closing, or will garbage handling take care of it for me?</p>