1

I am trying to build a blog webapi with this web api core demo and microsoft doc. I use Npgsql connect to a PostgreSQL database, and add some methods, but the database return error message "too many clients connected" when I debugging.

So how to close the connections in webapi? I read some documents but can't find a way to do with it.

my repo here

Rackar
  • 15
  • 5
  • I got a temporary way, Add "Pooling=false;" to my ConnectionStrings, because the max of the pool is 100, just escape the pooling way. – Rackar Nov 28 '18 at 05:43

1 Answers1

2

The easiest solution is to use using block. This will take care of database connection closing automatically and you don't have to manually close the database connection.

eg.

using (SqlConnection connection = new SqlConnection(connectionString))
{
   // Your database code
}
Aparna Gadgil
  • 410
  • 4
  • 9
  • Thanks, thats a good way to do, but in my case, i copy codes ```services.AddDbContext(option => option.UseNpgsql(Configuration.GetConnectionString("PostgreSql")));``` like this... – Rackar Dec 02 '18 at 16:32
  • You have to use dependency injection in this case. For detailed information on how to use this please refer this official documentation. https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext Also please refer this stackoverflow link for additional knowledge - https://stackoverflow.com/questions/40836102/asp-net-core-change-ef-connection-string-when-user-logs-in – Aparna Gadgil Dec 03 '18 at 12:08