MEF keeps reference of NonShared IDisposable parts, not allowing them to be collected by GC

自作多情 提交于 2019-11-28 08:29:15

Unless Prism supports some kind of lifetime for view objects, there is no solution here except to remove IDisposable from the list of interfaces exposed by the view.

There are three MEF approaches to handling this problem, all mentioned by other responders:

  • ExportFactory<T>
  • Child containers
  • ReleaseExport()

All of them require some work on the part of the code that requests the original export - in this case code within Prism. This makes some sense, as it is undesirable for code consuming an object to have to be aware of how and when it was created.

There is no ReleaseExportedObject() in MEF because multiple (e.g. property) exports can return the same value; it may be logically possible to provide but the added complexity makes it unlikely to be addressed by MEF in the foreseeable future.

Hope this helps; I've retagged this question 'prism' as I'm sure others in the Prism community will have encountered this and be able to offer advice.

When you implement IDisposable you are sort of saying that the type should be cleaned up in a deterministic way (by calling IDisposable.Dispose and not randomly when the garbage collector decides that it is time.

In your case the view models will only be disposed when you dispose the container which is probably not what you want to do. To get around this I see two possible solutions:

  • Don't implement IDisposable on your view models. Apparently you don't care about when they are cleaned up anyway so why make them IDisposable?

  • Instead of letting the container create each view model non-shared you could use a shared view model factory class. You can then inject that class into owners of view models to allow the owners to explicitely create view models. Presumeably these owners would also know when to dispose the view models.

Basically, if something is disposable that should also be a sensible point in your code where you need to dispose what is disposable.

Wim Coenen

You should create these instances via an imported ExportFactory<T>. You will then have the necessary control to dispose of them via ExportLifetimeContext<T>.Dispose().

However, this is only available out of the box in the next .NET version (4.5) or in the latest MEF preview releases on codeplex. (In older versions of MEF the same functionality was implemented as a sample and was called PartCreator, as described in this blog post.)

All the other answers provide good ways to circumvent this issue, but what I ended up doing eventually was using my own custom interface, ICleanup, instead of IDisposable. This of course may not be suitable for everyone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!