title: Npgsql, connection pool has been exhausted
body: <p>I started out with this - <a href="https://stackoverflow.com/questions/49383998/semaphoreslim-to-protect-the-connection-pool-from-exhaustion">SemaphoreSlim to protect the connection pool from exhaustion</a>, and quickly realized that my problem is that connections are not returned to the pool when I dispose of the DbContext.</p>
  
  <p>Consider that all connections to database is done within a using statement, as such:</p>
  
  <pre><code>using (var context = ContextFactory.GetContext&lt;PostgreSqlDatabaseContext&gt;(connectionString))
  {
      var query = $"SELECT * FROM public.\"MyTable\" WHERE \"MyId\" = '{id}'";
      var result = await context.MyTable.FromSql(query).SingleOrDefaultAsync();
      return result;
  }
  </code></pre>
  
  <p>The <code>ContextFactory</code> looks like this:</p>
  
  <pre><code>internal class ContextFactory
  {
      public static T GetContext&lt;T&gt;(string sqlConnection) where T : DbContext
      {
          var optionsBuilder = new DbContextOptionsBuilder&lt;PostgreSqlDatabaseContext&gt;();
          optionsBuilder.UseNpgsql(sqlConnection);
          return new PostgreSqlDatabaseContext(optionsBuilder.Options) as T;
      }
  }
  </code></pre>
  
  <p>Regardless of what I do with the connection string, setting <code>Enlist=true</code> as suggested <a href="https://github.com/npgsql/npgsql/issues/1483" rel="nofollow noreferrer">here</a>, or throttling connections using <code>SemaphoreSlim</code> as suggested <a href="https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/96" rel="nofollow noreferrer">here</a> I get the same result:</p>
  
  <blockquote>
    <p>The connection pool has been exhausted, either raise MaxPoolSize
    (currently 20) or Timeout (currently 15 seconds)</p>
  </blockquote>
  
  <p>Does <code>Npgsql</code> work at all? What is going on here?</p>
  
  <p>Note that I have read <a href="https://stackoverflow.com/questions/38495717/npgsql-connection-pool-stopping-at-minpoolsize-connections">this</a> and <a href="https://stackoverflow.com/questions/44272459/postgres-npgsql-connection-pooling">this</a> and they are not the same.</p>