Reputation: 317
I am writing a WPF application that uses MEF in .Net 4. My app has a CompositionContainer that is accessed by all my view models in order to get access to (using MEF) some shared objects that are responsible for data retrieval and storage.
I have been using a memory profiler to look at the lifetime of some of both my view model objects as well as the data access objects to see when everything is being garbage collected. To my surprise, I found that my app's CompositionContainer was keeping a reference to my view models after they had already been disposed.
The following is my attempt to show roughly how I'm using MEF. I'm hoping someone can show me how I'm doing it wrong.
Code in App.xaml.cs
public partial class App : Application { private static CompositionContainer _container; internal static CompositionContainer Container { get { return _container; } } private void OnStartup(object sender, StartupEventArgs e) { AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); _container = new CompositionContainer(catalog); } }
Contract interface
public interface ICostCentreService : IBaseEntityService { ... }
Exported class that implements interface
[PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(ICostCentreService))] public class CostCentreService : BaseEntityService, ICostCentreService { ... }
My view model class
public class CostCentreViewModel: ViewModelBase { [Import] private ICostCentreService _costCentreService;
public CostCentreViewModel() { App.Container.ComposeParts(this); }
}
Hopefully the code extracts above paint enough of a picture as to show how I am using MEF. The problem occurs once I have finished using the view model and I call Dispose and remove all references to it, it doesn't get garbage collected because the app's container still references it. (In the case I have on my screen at the moment, the memory profiler says my view model is still referenced by App._containner._partExportProvider._parts._items[0]._cashedIntance).
So I'm wondering how I get rid of this reference. Am I not using MEF properlly?
Any help would be much appreciated.
Cheers,
Nick Barrett
Upvotes: 0
Views: 221
Reputation: 16744
Shared parts won't be released until the container is disposed. A shared part means that only one will be created per container. The MEF container keeps a reference to it because if it is ever asked for that part again, it should return the one that was already created instead of creating a brand new one.
For NonShared parts, there are ways you can have MEF release the references to them.
Upvotes: 0