kernel-memory icon indicating copy to clipboard operation
kernel-memory copied to clipboard

[Bug] Dispose() not called for singleton services

Open vvdb-architecture opened this issue 5 months ago • 0 comments

Context / Scenario

For some reason I have not been able to determine, the KernelMemory builder creates its own service provider in various places, i.e. here and here.

However, singleton services that implement IDisposable should be disposed when their service provider is disposed. Since the service providers created by the KernelMemory builder are never disposed, the singleton's Dispose() is never called.

The problem is mitigated somewhat by the fact that many services are added to the service collection as direct instances: in that case, it's up to the creator of those instances to dispose them. This is documented (here)[https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#disposal-of-services].

But having a mechanism that does this at the right time (i.e. when using var host = hostBuilder.Build(); leaves the scope) is needlessly complicated and fragile.

What happened?

I've implemented an IMemoryDB that is attached to a Lucene.NET search engine. It implements IDisposable because the index writer needs to be disposed cleanly when the web service or console app is terminated. The Dispose() method is never called in the current implementation.

Since the IKernelMemory service is injected, I expected that at least its implementation would implement IDisposable and that it would dispose the necessary providers. That doesn't happen. The fix would be simple but there are two (!) instances of ServiceProvider created and I do not understand why.

Importance

a fix would make my life easier

Platform, Language, Versions

C#, Any platform/version

Relevant log output

N/A

vvdb-architecture avatar Jan 27 '24 07:01 vvdb-architecture