Wilko
Wilko

Reputation: 91

EF Core MySql connections not closing

We have developed a project in .NET Core and Entity Framework Core using the MySql nuget package.

The context is added to dependancy injection using the following line:

services.AddDbContext<ReadWriteContext>(options => options.UseMySQL(Configuration["Machine:ReadWriteConnectionString"]));

Then in a controller, this is injected as such:

public class SystemController : Controller
{
    private readonly ReadWriteContext _dataContext;

    public SystemController(ReadWriteContext dataContext)
    {
        _dataContext = dataContext;
    }

    ...

}

And used as such:

var hasServices = await _dataContext.Services.AnyAsync();

In the logs we see the opening and closing log lines:

Opening connection to database 'config_service' on server '10.211.55.5'.
Closing connection to database 'config_service' on server '10.211.55.5'.

However, when we look at the MySql server and run "show full processlist", the connections are still showing as being in the sleep state and never close. When you stop the .NET process, the connections then close and disappear from MySql process list.

How do I get the connections to close when the request is finished. The AddDbContext should be scoped to the current request, but it does not appear to properly close the connections.

Any help would be great?

Upvotes: 1

Views: 2133

Answers (1)

tschmit007
tschmit007

Reputation: 7800

I'm not aware with MySql. That said if you were in a SQL server context you would be facing the "connection pool": https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling.

That is your application keep a set of active connection to speed up the process of reaching the data server. Thus even if you sais to the pool "I don't need this connection anymore", it does not believe you and keep the connection open... just in case.

For how long, well it depends on logic beyond the scope of the application. One use to say: it is the connection pool realm, just let it do his job.

So the answer for your question is: you can't explicitly close the connection to the server. The connection pool will decide when to close or not.

Upvotes: 1

Related Questions