Проблема с обновлением подключаемого модуля времени выполнения MEF

Проблема

My MEF code is not appropriately updating assemblies during runtime, from a folder associated to a DirectoryCatalog. The plugins load at run-time succesffully, but when i update the dll and call Refresh on the DirectoryCatalog, the assemblies are not getting updated.

Задний план

I am building a dll that has an MEF container, and uses a DirectoryCatalog to find a local plugin folder. I call this dll currently from a simple WinForm, that is setup to with a seperate project to use ShadowCopy so i can overwrite the dlls in my plugin folder. Instead of using a FileWatcher to update this folder, I am exposing a public method that calls refresh on the DirectoryCatalog, so i can update the assemblies at will instead of automatically.

Код

базовый класс создает каталоги и контейнер MEF и сохраняет их как переменные класса для последующего ссылочного доступа

    public class FieldProcessor
{
    private CompositionContainer _container;
    private DirectoryCatalog dirCatalog;

    public FieldProcessor()
    {
        var catalog = new AggregateCatalog();
        //Adds all the parts found in the same assembly as the TestPlugin class
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(TestPlugin).Assembly));
        dirCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory + "Plugin\\");
        catalog.Catalogs.Add(dirCatalog);

        //Create the CompositionContainer with the parts in the catalog
        _container = new CompositionContainer(catalog);
    }

    public void refreshCatalog()
    {
        dirCatalog.Refresh();
    }

} ...

вот плагин, который я пытаюсь перезаписать. Мой тест обновления заключается в том, что возвращенные строки выводятся в текстовое поле, я изменяю строки, которые возвращает плагин, перестраиваю и копирую их в папку плагина. Но он не обновляется для работающего приложения, пока я не закрою и не перезапущу приложение.

[Export(typeof(IPlugin))]
[ExportMetadata("PluginName", "TestPlugin2")]
public class TestPlugin2 : IPlugin
{
    public IEnumerable<IField> GetFields(ContextObject contextObject, params string[] parameters)
    {
        List<IField> retList = new List<IField>();
        //Do Work Return Wrok Results
        retList.Add(new Field("plugin.TestPlugin2", "TestPluginReturnValue2"));
        return retList;
    }
}

Редактировать

Import Statement

    [ImportMany(AllowRecomposition=true)]
    IEnumerable<Lazy<IPlugin, IPluginData>> plugins;

Исследовательская работа

I have done fairly extensive research and everywhere in articles and code samples the answer appears to be, to add a DirectoryCatalog to a container and save a reference of that catalog, then call Refresh on that reference, after a new plugin has bee added, and it will update the assemblies...which i am doing, but it's not showing updated output, from the new plugin dll.

Запрос

Has anyone seen this issue, or know what may be causing my problems with the assemblies not updating during runtime? Any additional information or insight would be appreciated.

разрешение

Thanks to Panos and Stumpy for their links which led me to the solution my issue. For future knowledge seekers, my main issue was that the Refresh method does not update assemblies, when the new assembly has the exact same assembly name as the overwritten dll. For my POC i just tested rebuilding with a Date appended to the assembly name and everything else the same, and it worked like a charm. their links in the comments below, were very useful, and are recommended if you have the same issue.


person Mabdullah    schedule 22.04.2013    source источник
comment
DirectoryCatalog.Refresh не обнаруживает обновленные сборки. Только новые или удаленные. Посмотрите на этот ответ обходной путь и предложения: stackoverflow.com/a/14842417/850119   -  person Panos Rontogiannis    schedule 23.04.2013
comment
Мои библиотеки DLL заблокированы, когда они загружены, поэтому я не могу заменить их новыми DLL. У вас не было этой проблемы? вы сделали что-то, что сделало их обновляемыми?   -  person Poul K. Sørensen    schedule 18.12.2013
comment
да, у меня была эта проблема. Одним из шагов, которые я упомянул мимоходом, было включение теневого копирования. Shadow Copy позволяет программе создавать локальные копии сборок dll и добавлять их в локальный кеш вместо блокировки dll. Это должно быть включено, чтобы вы могли выполнять горячую замену DLL во время выполнения, в противном случае вам нужно остановить программу, изменить библиотеки DLL, а затем перезапустить ее. Я думаю, что это тот пример, на который я смотрел, но если он не работает для вас, Google MEF и Shadow Copy, stackoverflow.com/questions/12593308/   -  person Mabdullah    schedule 04.02.2014


Ответы (1)


вы установили параметр AllowRecomposition для атрибута импорта?

AllowRecomposition
Gets or sets a value that indicates whether the property or field will be recomposed when exports with a matching contract have changed in the container.

http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.importattribute(v=vs.95).aspx

редактировать:

DirectoryCatalog не обновляет сборки, а только добавляет или удаляет: http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog.refresh.aspx

для работы: https://stackoverflow.com/a/14842417/2215320

person Niels    schedule 22.04.2013
comment
Я сделал, извините, я изначально не публиковал код оператора импорта, я обновил вопрос, чтобы отразить мой оператор импорта. - person Mabdullah; 23.04.2013
comment
а ваш код обновления? Думаю проблема внутри. Вы сказали, что не используете FileSystemWatcher, как вы обнаруживаете и перезагружаете свои сборки? - person Niels; 23.04.2013
comment
Я показываю это с помощью метода RefreshCatalog, показанного выше. Я вызываю этот метод из события нажатия кнопки в winForm. - person Mabdullah; 23.04.2013
comment
Обновление не обновляет сборки, а только добавляет или удаляет их. msdn.microsoft.com/en- us / library / см .: stackoverflow.com/a/14842417/2215320 - person Niels; 23.04.2013
comment
спасибо за ссылки, которые я исследую дальше, возможно, придется немного изменить вариант использования, но похоже, что они очень помогут. Я отвечу и отмечу это как ответ, как только у меня все получится. Еще раз спасибо. - person Mabdullah; 23.04.2013
comment
Это была проблема именования сборок, как только я получил код для использования уникальных имен сборок, код работал как чемпион. Спасибо за вашу помощь. - person Mabdullah; 24.04.2013