title: Nhibernate, SQL Server and IIS 7.5 Connection leak : Timeout prior to obtaining a connection from the app pool
body: <p>I have an MVC application deployed on 3 separate servers (Test, Staging and Production Environment). Test and Staging server are doing fine but occassionally, the production server do pull this error</p>
  
  <blockquote>
    <p>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>The full stack trace as captured by elmah is as shown below.</p>
  
  <p><a href="https://i.stack.imgur.com/BqrkA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BqrkA.jpg" alt="Timeout error message"></a></p>
  
  <p>The production server is on SQL Server 2008 and IIS 7.5.</p>
  
  <p>My Nhibernate Driver connector is as shown below</p>
  
  <pre><code> &lt;?xml version="1.0" encoding="utf-8" ?&gt;
  &lt;hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"&gt;
  &lt;session-factory&gt;
      &lt;property    name="dialect"&gt;NHibernate.Dialect.MsSql2008Dialect,NHibernate&lt;/property&gt;
      &lt;property name="adonet.batch_size"&gt;0&lt;/property&gt;
      &lt;property name="show_sql"&gt;true&lt;/property&gt; 
      &lt;mapping assembly="BusinessLogic"/&gt;
  &lt;/session-factory&gt;
  &lt;/hibernate-configuration&gt;
  </code></pre>
  
  <p>Here is my Get current session Method</p>
  
  <pre><code> public static ISession GetCurrentSession()
          {
              HttpContext context = HttpContext.Current;
              ISession currentSession = context.Items[CURRENT_NHIBERNATE_SESSION_KEY] as ISession;
  
              if (currentSession == null)
              {
                  currentSession = sessionFactory.OpenSession();
                  context.Items[CURRENT_NHIBERNATE_SESSION_KEY] = currentSession;
              }
              if (currentSession.Connection.State == System.Data.ConnectionState.Closed)
              {
                  currentSession = sessionFactory.OpenSession();
              }
              if (!currentSession.IsConnected)
              {
                  currentSession = sessionFactory.OpenSession();
              }
              if (!currentSession.IsOpen)
              {
                  currentSession = sessionFactory.OpenSession();
              }
              if (currentSession.IsDirty())
              {
                  currentSession.Clear();
              }
  
              return currentSession;
          }
  </code></pre>
  
  <p>I used IRepository pattern for all my business logic. One of my method is shown here:</p>
  
  <pre><code> public IList&lt;CourseRequirement&gt; getCourseRequirement(int requirementId)
              {
                  ISession  session = _courseRequirment.CurrentSession;
                  var cr = session.QueryOver&lt;CourseRequirement&gt;().Where(x =&gt; x.RequirementId == requirementId);
                  return cr.List&lt;CourseRequirement&gt;();
              }
  </code></pre>
  
  <p>In addition, I am using autofac for dependency injection. I can also see this in the inner exception every time it happens.</p>
  
  <blockquote>
    <p>System.InvalidOperationException: An error occurred when trying to
    create a controller of type 'ASSEMBLY.Controllers.AccountController'.
    Make sure that the controller has a parameterless public constructor.
    ---> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor()' on type
    'NHibernateRepository`2'. ---> 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. (See inner exception for 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><strong>What I have done</strong> </p>
  
  <p>I have checked these <a href="https://stackoverflow.com/questions/21039206/getting-timeout-expired-the-timeout-period-elapsed-prior-to-obtaining-a-connect">link</a>, <a href="https://stackoverflow.com/questions/9398323/how-to-fix-sql-connection-leaks-in-this-code">link</a> and many more. Others like <a href="http://how-to-fix-sql-connection-leaks-in-this-code" rel="nofollow noreferrer">how-to-fix-sql-connection-leaks-in-this-code</a> suggested  putting the sql in using statements. 
  Almost, all the links suggested connection leak in the application and recommends putting all transaction in a using statement.</p>
  
  <p>Implement that implies rewriting most methods in my business logic.</p>
  
  <p>I am worried because this is not the only application I have written this way and besides Test and staging environment are fine. From logging report, this often happens when the site is on low traffic e.g 6:00 am, 3.00 am but the time is not fixed.</p>
  
  <p>Kindly help </p>
  
  <p><strong>Update</strong>
  This is my autofac Dependency resolver(I can see from the inner exception that autofac could not instantiate some services occasionally</p>
  
  <pre><code> public class FormDependencyResolver
      {
          public static void RegisterDependencies()
          {
  
              var builder = new ContainerBuilder();
  
              builder.RegisterControllers(typeof(MvcApplication).Assembly);
  
  
              builder.Register(c =&gt;
                  //register FakeHttpContext when HttpContext is not available
                  HttpContext.Current != null ?
                  (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) :
                  (new FakeHttpContext("~/") as HttpContextBase))
                  .As&lt;HttpContextBase&gt;()
                  .InstancePerLifetimeScope();
              builder.Register(c =&gt; c.Resolve&lt;HttpContextBase&gt;().Request)
                  .As&lt;HttpRequestBase&gt;().InstancePerLifetimeScope();
  
              builder.Register(c =&gt; c.Resolve&lt;HttpContextBase&gt;().Response)
                  .As&lt;HttpResponseBase&gt;()
                  .InstancePerLifetimeScope();
              builder.Register(c =&gt; c.Resolve&lt;HttpContextBase&gt;().Server)
                  .As&lt;HttpServerUtilityBase&gt;()
                  .InstancePerLifetimeScope();
              builder.Register(c =&gt; c.Resolve&lt;HttpContextBase&gt;().Session)
                  .As&lt;HttpSessionStateBase&gt;()
                  .InstancePerLifetimeScope();
  
  
  
              builder.RegisterGeneric(typeof(NHibernateRepository&lt;,&gt;)).As(typeof(IRepository&lt;,&gt;)).InstancePerLifetimeScope();
              builder.RegisterType&lt;AsyncService&gt;().As&lt;IAsyncService&gt;().InstancePerLifetimeScope();//.InstancePerLifetimeScope();
              builder.RegisterType&lt;SMSSender&gt;().As&lt;ISMSSender&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;SMSAccount&gt;().As&lt;ISMSAccount&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;BusinessLogic.Services.AuthenticationService&gt;().As&lt;IAuthenticationService&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;PageHelper&gt;().As&lt;IPageHelper&gt;().InstancePerLifetimeScope();
  
              builder.RegisterType&lt;UtilityService&gt;().As&lt;IUtilityService&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;WebWorker&gt;().As&lt;IWebWorker&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;DateTimeHelper&gt;().As&lt;IDateTimeHelper&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;UserService&gt;().As&lt;IUserService&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;AuditService&gt;().As&lt;IAuditService&gt;().InstancePerLifetimeScope();
              builder.RegisterType&lt;HtmlHelper&gt;().InstancePerDependency();
              builder.RegisterType&lt;PaymentService&gt;().As&lt;IPaymentService&gt;().InstancePerLifetimeScope();
  
              IContainer container = builder.Build();
              DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  
          }
      }
  </code></pre>