EFCore - Memory not released for DbContexts taking externally created DbConnection
Posted: Tue 11 Sep 2018 11:25
Consider an application doing the following:
With a DbContext configured as:
Memory will continuously increase and will never be freed, ultimately resulting in an OutOfMemoryException.
The issue can be resolved if the DbContext takes ownership over the underlying DbConnection, e.g by configuring as:
In which case disposing of the context will successfully release all associated resources.
To be fair I'm not sure if this is dotConnect's fault here or if it's EFCore. Since UseOracle is your extension I'm raising the issue here to start with.
Let me know if you need a sample project for this but since this is easy to reproduce the above should suffice.
Code: Select all
while (true)
{
using (var conn = new OracleConnection("your connection string"))
using (var dbContext = new MyDbContext(conn))
DoQueries(dbContext); // Actual work is irrelevant, as long as this is doing some DB access in order to prime the DbContext
}
Code: Select all
public class MyDbContext : DbContext
{
private readonly IDbConnection _dbConnection;
public MyDbContext(IDbConnection dbConnection) => _dbConnection = dbConnection;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder.UseOracle(_dbConnection as DbConnection);
}
(...)
}
The issue can be resolved if the DbContext takes ownership over the underlying DbConnection, e.g by configuring as:
Code: Select all
optionsBuilder.UseOracle("your connection string");
To be fair I'm not sure if this is dotConnect's fault here or if it's EFCore. Since UseOracle is your extension I'm raising the issue here to start with.
Let me know if you need a sample project for this but since this is easy to reproduce the above should suffice.