I am writing an application targeting the dotnet core framework 3.1. I use dependency injection to configure, among others, the database context. In my Program.cs I have the following code:
var host = new HostBuilder()
.ConfigureHostConfiguration(cfgHost =>
{
...
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
....
})
.ConfigureServices((hostContext, services) =>
{
...
services.AddDbContext<MyHomeContext>(options =>
{
options.UseNpgsql(hostContext.Configuration.GetConnectionString("DbContext"));
}, ServiceLifetime.Transient);
...
})
.ConfigureLogging((hostContext, logging) =>
{
...
})
.Build();
I pass host
to another class. In that other class I have, as part of a longer method, the following code:
using (var context = Host.Services.GetService(typeof(MyHomeContext)) as MyHomeContext)
{
StatusValues = context.Status.ToDictionary(kvp => kvp.Name, kvp => kvp.Id);
}
GC.Collect();
GC.Collect();
The GC.Collect
calls are there for testing / investigation purposes. In MyHomeContext
I, for testing purposes, implemented a destructor and an override of Dispose().
Dispose() gets called, but the destructor never gets called.
This results in a memory leak for every instance of MyHomeContext
I create.
What am I missing? What can I do the make sure the the instance of MyHomeContext
gets deleted when I no longer need it.
I moved to this implement because of a few reasons:
- I only need a database connection for a short amount of time.
- I insert a lot of data (not in the above reduced example / test code), resulting in the DbContext keeping a large cache. I expected disposing the object would free the memory, but now I only made it worse :(
When I replace Host.Services.GetService(typeof(MyHomeContext)) as MyHomeContext
by new MyHomeContext()
the destructor of MyHomeContext
is being called. Seems, to me, that something in the dependency injection framework is holding a reference to the object. Is this true? If so, how can I tell it to release it?