The container has no way of knowing when the transient object has been freed. In Maui unless you implement scopes, transient objects should not require dispose. Use a singleton injected factory. note: if the container did not have a ref to the object, it could not call dispose and would be a major limitation.
Why does DI container retain references to transient instances that are IDisposable?
https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#disposable-transient-services-captured-by-container says, "by default the DI container will hold onto these references, and not Dispose() of them until the container is disposed when application stops if they were resolved from the container."
In addition, the documentation says, "The receiver of the IDisposable dependency shouldn't call Dispose on that dependency."
In a C# MAUI app, the DI container lifetime is the same as the app lifetime. So disposing of the container to get the transient IDisposable items to free up is not really a viable option. for view models and views.
Bottom line, if a transient
instance is defined, it will be disposed when no longer referenced, UNLESS it implements IDisposable
. In my testing, this has proven to be the case. Once there are no references in our application code to the transient instances, the GC dump shows that the DI service is holding a reference to the instance and keeping them from being garbage collected. The result is that all of the items where we would like to unsubscribe from events in the ``` Dispose()` methods are being retained in memory and resulting in memory leaks. Now that we have discovered this unexpected behavior, we can work around it. ``
I would like to understand why this counterintuitive behavior from the DI container of holding onto transient items that are `IDisposable
? Instead, I would expect the container itself to call Dispose() and then release the instances. Please enlighten.
What is a good programming pattern for a MAUI app to inject transient items that may need to unsubscribe before being finalized?
Developer technologies | C#
1 answer
Sort by: Most helpful
-
Bruce (SqlWork.com) 78,316 Reputation points Volunteer Moderator
2025-06-30T23:42:39.4633333+00:00