2012-02-26 102 views
6

DirectoryCatalog扫描目录中的程序集以确定导入/导出哪些类。没有导入/导出的任何程序集都不加载。MEF的DirectoryCatalog如何工作?

这是一个很棒的功能,但它是如何工作的?要调查程序集中类型的自定义属性,是否需要加载程序集?一旦它被加载,它就不能被卸载,所以不能如何工作。

它在做某种AppDomain的魔法吗?

回答

10

试一试。 DirectoryCatalog仅为给定目录中的每个.dll文件创建一个AssemblyCatalog。由于AssemblyCatalog调用的是AssemblyName.GetAssemblyName,因此不会加载非.NET的.dll文件(抛出异常并将其捕获到AssemblyCatalog中)。 AssemblyCatalogAssemblyName上调用Assembly.Load它创建。因此,创建一个DirectoryCatalog时立即加载程序集。没有魔法,没有AppDomains。但是然后MEF是众所周知的加载组件到当前AppDomain。如果您想要可以卸载的组件,请使用MAF

+0

不幸的是,MAF已经过时了,并且由于使用了远程处理而带来了很大的限制。我还没有找到一个好的选择。虽然我没有意识到MEF加载了程序集。 – 2012-02-27 01:15:15

+0

你是什么意思“可以卸载的组件”? – Assimilater 2017-06-22 19:36:13

1

这是可以帮助你的示例代码。

var directoryPath = "Dll folder path"; 

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

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

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

container.ComposeParts(this); 


[ImportMany] 
public List<IModule> Modules { get; set; } 
+4

这有助于回答我的问题吗? – 2012-03-05 14:32:58

+0

这是目录编目的执行。如何使用此代码获取模块, – 2012-03-06 05:33:25

+4

这与我的问题有什么关系? – 2012-03-06 12:58:57