MEF的DirectoryCatalog如何工作?

时间:2012-02-26 21:20:14

标签: c# reflection assemblies mef appdomain

DirectoryCatalog扫描目录中的程序集以确定导入/导出的类。未加载任何没有导入/导出的程序集。

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

它正在做某种AppDomain魔术吗?

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分: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; }