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

前端 未结 4 1790
一整个雨季
一整个雨季 2020-12-09 05:11

I\'ve encountered somewhat of a problem in MEF\'s part lifetime which causes memory leaks in my Prism application.

My application exports views and viewmodels with t

4条回答
  •  无人及你
    2020-12-09 05:23

    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.

提交回复
热议问题