I started out with this - SemaphoreSlim to protect the connection pool from exhaustion, and quickly realized that my problem is that connections are not returned to the pool when I dispose of the DbContext.
Consider that all connections to database is done within a using statement, as such:
using (var context = ContextFactory.GetContext<PostgreSqlDatabaseContext>(connectionString))
{
var query = $"SELECT * FROM public.\"MyTable\" WHERE \"MyId\" = '{id}'";
var result = await context.MyTable.FromSql(query).SingleOrDefaultAsync();
return result;
}
The ContextFactory
looks like this:
internal class ContextFactory
{
public static T GetContext<T>(string sqlConnection) where T : DbContext
{
var optionsBuilder = new DbContextOptionsBuilder<PostgreSqlDatabaseContext>();
optionsBuilder.UseNpgsql(sqlConnection);
return new PostgreSqlDatabaseContext(optionsBuilder.Options) as T;
}
}
Regardless of what I do with the connection string, setting Enlist=true
as suggested here, or throttling connections using SemaphoreSlim
as suggested here I get the same result:
The connection pool has been exhausted, either raise MaxPoolSize (currently 20) or Timeout (currently 15 seconds)
Does Npgsql
work at all? What is going on here?
Note that I have read this and this and they are not the same.