Search code examples
c#mefdispose

Problem with MEF - ExportFactory<T> - call Dispose method


If possible call dispose method on object which is created with ExportFactory?

Factory is here:

public  interface IViewModelsControler
{
    IChatViewModel CreatChatViewModel();
}

[Export(typeof(IViewModelsControler))]
public class ViewModelsControler:IViewModelsControler
{

    [Import]
    public ExportFactory<IChatViewModel> ChatViewFactory { get; set; }

    public IChatViewModel CreatChatViewModel()
    {
        return ChatViewFactory.CreateExport().Value;
    }
}

Creation of object:

var chatScreen = ViewModelControler.CreatChatViewModel();

I would like call chatScreen.Dispose().

ChatViewModel call look like this:

[Export(typeof(IChatViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ChatViewModel : Screen, IChatViewModel
    {}

Solution

  • You should call dispose on the ExportLifetimeContext returned by the call to CreateExport(), not on the exported value itself. This will dispose not just the ViewModelController, but any NonShared disposable parts that were created to satisfy its imports.