We use MEF (.NET 4, we cannot use 4.5 at the moment) in the MVVM application. Everything was fine until we needed to create models on the fly, for example, editable table rows. I do not want to work in memory leaks, I found this article http://pglazkov.blogspot.ch/2011/04/mvvm-with-mef-viewmodelfactory.html and I found an unexpected behavior that I would like to understand. This is an item added to the Shell.Items collection:
[PartCreationPolicy(CreationPolicy.NonShared)] [Export] public class Item : INotifyPropertyChanged, IDisposable { [Import] private Lazy<Shell> shell;
And this is the factory:
[PartCreationPolicy(CreationPolicy.Shared)] [Export] public class ChildContainerItemFactory : ItemFactory { public override Item Create() { var container = ServiceLocator.Current.GetInstance<CompositionContainer>(); using (var childContainer = CreateTemporaryDisposableContainer(container)) { var item = childContainer.GetExportedValue<Item>(); item.Initialize(); return item; } } [..] }
If I use this code, Item is along with the child container. If I change it to:
public override Item Create() { var container = ServiceLocator.Current.GetInstance<CompositionContainer>(); using (var childContainer = CreateTemporaryDisposableContainer(container)) { var item = new Item(); childContainer.SatisfyImportsOnce(item); item.Initialize(); return item; } }
The item is no longer placed in the container. I would like to understand if it is dangerous to use the GetExportedValue method (I use this method in other parts of the application) and which is the best practice to avoid memory leaks with for viewing models with short lifetimes.
Any help appreciated
source share