Castle Windsor IoC - Singleton/Transient 引用导致内存泄漏
Castle Windsor IoC - Memory leaks with Singleton/Transient references
我有一个 WPF 应用程序,它使用 IOC 和带有构造函数注入的根组合模式。视图模型的构造函数中的大多数参数都是存储库。一些存储库在缓存内容时使用单例生活方式。所有视图模型都是瞬态的,因为我希望在视图关闭后立即释放内存。
然而,在瞬态视图模型中引用单例存储库会在它们不再使用后将它们全部保留在内存中,从而阻止 IOC 容器释放它们。
有没有一种模式可以让我在不再使用时释放 类?我正在考虑在 ViewModel 上实现 IDisposable 并将存储库引用设置为 null,但这听起来不对。
根据 Castle Project 的一位提交者的博客:
Must I release everything when using Windsor?
Transient components are similar to pooled, because there’s no well known end to transient component’s lifetime, and Windsor will not know if you still want to use a component or not, unless you explicitly tell it (by calling Release). Since transient components are by definition non-shared Windsor will immediately destroy the component when you Release it.
根据他的另一篇帖子:
Must Windsor track my components?
Windsor by default will track objects that themselves have any decommission concerns, are pooled, or any of their dependencies is tracked.
Now seriously – often people see that Windsor holds on to the components it creates as a memory leak (it often is, when used inappropriately which I’ll talk about in the next post), and they go – Windsor holding on to the objects causes memory leaks, so lets use the NoTrackingReleasePolicy and the problem is solved.
因此我们可以说,除非您明确释放它们,否则 Windsor 几乎总是会保留对您的瞬态和池化对象的引用。
您的问题的一个优雅解决方案是编写一个自定义 LifestyleManager 以在您的应用程序不再需要它们时释放您的视图模型。
我有一个 WPF 应用程序,它使用 IOC 和带有构造函数注入的根组合模式。视图模型的构造函数中的大多数参数都是存储库。一些存储库在缓存内容时使用单例生活方式。所有视图模型都是瞬态的,因为我希望在视图关闭后立即释放内存。
然而,在瞬态视图模型中引用单例存储库会在它们不再使用后将它们全部保留在内存中,从而阻止 IOC 容器释放它们。
有没有一种模式可以让我在不再使用时释放 类?我正在考虑在 ViewModel 上实现 IDisposable 并将存储库引用设置为 null,但这听起来不对。
根据 Castle Project 的一位提交者的博客:
Must I release everything when using Windsor?
Transient components are similar to pooled, because there’s no well known end to transient component’s lifetime, and Windsor will not know if you still want to use a component or not, unless you explicitly tell it (by calling Release). Since transient components are by definition non-shared Windsor will immediately destroy the component when you Release it.
根据他的另一篇帖子:
Must Windsor track my components?
Windsor by default will track objects that themselves have any decommission concerns, are pooled, or any of their dependencies is tracked.
Now seriously – often people see that Windsor holds on to the components it creates as a memory leak (it often is, when used inappropriately which I’ll talk about in the next post), and they go – Windsor holding on to the objects causes memory leaks, so lets use the NoTrackingReleasePolicy and the problem is solved.
因此我们可以说,除非您明确释放它们,否则 Windsor 几乎总是会保留对您的瞬态和池化对象的引用。
您的问题的一个优雅解决方案是编写一个自定义 LifestyleManager 以在您的应用程序不再需要它们时释放您的视图模型。