title: Using singleton pattern with Entity Framework context - The underlying provider failed on open
body: <p>I'm trying to add a singleton pattern to my DbContext with Entity Framework. I've always used the singleton pattern for this, and never experienced this error before. <em>I know that singleton is best practice</em> <strong>(Apparently not)</strong>, <em>but if any of you have the time to spare, could you please explain why singleton is best practice?</em></p>
  
  <p><strong>Problem</strong></p>
  
  <p>Other than that, I get this error:</p>
  
  <blockquote>
    <p>The underlying provider failed on open</p>
  </blockquote>
  
  <p><strong>Let's have a look at my code</strong></p>
  
  <p><em>DAO.cs</em></p>
  
  <pre><code>public class DAO
  {
      private static HourRegistrationEntities hourRegInstance;
  
      public static HourRegistrationEntities HourRegInstance { get { return hourRegInstance = hourRegInstance ?? new HourRegistrationEntities(); } }
  }
  </code></pre>
  
  <p><em>Service.cs (example method)</em></p>
  
  <pre><code>/// &lt;summary&gt;
  /// Return a list of all denied Hour Registration for the Login with the given stringId
  /// &lt;/summary&gt;
  /// &lt;param name="stringId"&gt;&lt;/param&gt;
  /// &lt;returns&gt;A list of HourRegistrationDTO&lt;/returns&gt;
  public List&lt;HourRegistrationDTO&gt; GetAllDeniedHoursForLogin(string stringId)
  {
      var id = Int32.Parse(stringId);
      using (var db = DAO.HourRegInstance)
      {
          var dbHours = db.HourRegistration.Where(x =&gt; x.LoginProject.Login.ID == id &amp;&amp; x.Denied == true).ToList();
          var returnList = new List&lt;HourRegistrationDTO&gt;();
          foreach (var item in dbHours)
          {
              returnList.Add(new HourRegistrationDTO()
              {
                  Id = item.ID,
                  Hours = item.Hours,
                  Date = item.Date.ToShortDateString(),
                  Comment = item.Comment,
                  CommentDeny = item.CommentDeny,
                  LoginProject = new LoginProjectDTO()
                  {
                      Project = new ProjectDTO()
                      {
                          Title = item.LoginProject.Project.Title
                      }
                  }
              });
          }
           return returnList;
      }            
  }
  </code></pre>
  
  <p>As mentioned, I've <strong>ALWAYS</strong> used the singleton pattern but <strong>NEVER</strong> had this error before. What's causing this, and why?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I basically do like this (code below) instead, as that solves the problem. Now I'm more curious about what's causing the error.</p>
  
  <p><em>Service.cs</em></p>
  
  <pre><code>using (var db = new HourRegistrationEntities())
  </code></pre>