我有一个包含许多.dll的目录,其中一些是我使用DirectoryCatalog
加载的MEF插件 - 例如:
var catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
这会将执行目录的主机上的所有程序集加载到目录中。但是,我希望只建立一个MEF组件目录(即可组合部件)。
有没有办法检测MEF组件?
答案 0 :(得分:6)
没有MEF部件的组件对DirectoryCatalog.Parts
没有任何影响,因此MEF已经为您进行了检测。
如果您认为扫描MEF部件的所有部件对性能的影响太大,那么您可以使用search pattern来过滤DLL名称,如下所示:
var catalog = new DirectoryCatalog(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"*.plugins.dll");
答案 1 :(得分:1)
这是一个你应该能够插入并用于修复ReflectionTypeLoadException问题的类。
using System;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Your.Namespace
{
public class SafeDirectoryCatalog : AggregateCatalog
{
public SafeDirectoryCatalog(string folderLocation)
{
var di = new DirectoryInfo(folderLocation);
if (!di.Exists) throw new Exception("Folder not exists: " + di.FullName);
var dlls = di.GetFileSystemInfos("*.dll");
foreach (var fi in dlls)
{
try
{
var ac = new AssemblyCatalog(Assembly.LoadFile(fi.FullName));
var parts = ac.Parts.ToArray(); // throws ReflectionTypeLoadException
this.Catalogs.Add(ac);
}
catch (ReflectionTypeLoadException ex)
{
//Swallow this exception
}
}
}
}
}