Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memory leak issue caused by IDisposable (?) #123

Closed
yunusefendi52 opened this issue Oct 1, 2022 · 1 comment
Closed

Memory leak issue caused by IDisposable (?) #123

yunusefendi52 opened this issue Oct 1, 2022 · 1 comment

Comments

@yunusefendi52
Copy link

I am trying to understand the generated code and found out that there is List<object>? _disposables; which keeps the IDisposable object from the service, but I think that also causes the object to leak(?), here is the test to check if the object is leaking:

var p = new MyServiceProvider();
WeakReference w = new(null);
var i = new Action(() =>
{
    var service = p.GetService<IService>();
    w.Target = service;
});
i();
GC.Collect();
Console.WriteLine($"Is the object still alive? {w.IsAlive}");

If the service doesn't implement IDisposable the object didn't leak, but if it does it leak

My use case is that the provider is alive as long as the app still running, I am using dotnet android

@pakrym
Copy link
Owner

pakrym commented Oct 11, 2022

This is possible when the service is registered as transient but also implements IDisposable interface. Because it's transient, a new instance is created every time is requested. The container is supposed to track the lifetime of all services it creates, so it stores the service in the _disposables list. But the _disposables are only disposed when you call .Dispose() on the container itself, meaning that their lifetime is extended to the lifetime of the container.

This problem doesn't happen if you resolve disposable transients from a scope that's returned by CreateScope as it can be disposed earlier than the entire container is.

Similar issue in the Microsoft DI :aspnet/DependencyInjection#456

@pakrym pakrym closed this as not planned Won't fix, can't repro, duplicate, stale Dec 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants