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

蓝咒 提交于 2019-12-11 04:41:27

问题


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
    {}

回答1:


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.




回答2:


Your contract for chatScreen needs to expose the Dispose() method.

public interface IViewModelsControler
{
    IChatViewModel CreatChatViewModel();
    void Dispose();    // add to expose your dispose method
}

Here is another answer regarding garbage collection if that is what you are after.



来源:https://stackoverflow.com/questions/4597317/problem-with-mef-exportfactoryt-call-dispose-method

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