2012-02-29 51 views
6

我有一些插件作爲dll文件。我的應用程序加載的DLL,它運行良好。但是當我嘗試刪除舊插件並將其替換爲新插件時,它不允許執行此操作。因爲它已被應用程序加載。我發現通過使用appdomain,我們可以做到這一點。但我無法找到使用mef的解決方案。卸載mef中的dll文件

我需要一個可以在mef上運行的代碼。以下是我用來加載插件的代碼。

//Creating an instance of aggregate catalog. It aggregates other catalogs 
var aggregateCatalog = new AggregateCatalog(); 

//Build the directory path where the parts will be available 
var directoryPath = "Path to plugins folder"; 

//Load parts from the available dlls in the specified path using the directory catalog 
var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll"); 

//Add to the aggregate catalog 
aggregateCatalog.Catalogs.Add(directoryCatalog); 

//Crete the composition container 
var container = new CompositionContainer(aggregateCatalog); 


// Composable parts are created here i.e. the Import and Export components assembles here 
container.ComposeParts(this); 

回答

4

我已經發現,通過使用AppDomain中,我們可以做到這一點。但我無法找到使用mef的解決方案。

不幸的是,這不被MEF支持。 MEF專爲應用程序擴展性而設計,而不是作爲支持在運行時卸載和替換代碼的通用插件系統。

使這項工作的唯一方法是在單獨的AppDomain中使用MEF,並作爲一個整體卸載AppDomain。除卸載打開程序集的整個AppDomain之外,CLR本身不支持卸載加載的程序集。

+0

應該有一個解決方案。我聽說這將在mef下一個版本中發佈。不知道它是真的還是不是。 – 2012-02-29 07:23:04

+1

@fhnaseer沒有 - 至少在目前沒有公開顯示的任何東西。這確實超出了MEF的預期用例,所以我懷疑它會在那裏發生。只有在CLR中刪除程序集的支持方式是卸載整個AppDomain。作爲圖書館的MEF不能「解決」這個問題。 – 2012-02-29 07:32:22

+0

那麼ImportMany中的「AllowRecomposition = true」是什麼意思?如果我寫或不寫,行爲是一樣的。 – 2012-02-29 07:47:12

1

如果你試圖在目錄中插入一個組合對象是這樣的:

Assembly assembly = Assembly.Load(System.IO.File.ReadAllBytes(Path.Combine(directoryPath, ItemPlugin))); 
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assembly)); 

您可以刪除/後更改文件...

+1

您可以從aggregateCatalog中將其刪除,但無法從appdomain卸載程序集而無需卸載孔appdomain。 – Peter 2014-10-20 12:49:24