gpt4 book ai didi

c# - 在 MEF 组合期间处理 ReflectionTypeLoadException

转载 作者:IT王子 更新时间:2023-10-29 04:28:26 26 4
gpt4 key购买 nike

我在 MEF 中使用 DirectoryCatalog 来满足我应用程序中的导入。但是,当我尝试编写目录时,目录中有时会出现混淆程序集,导致 ReflectionTypeLoadException

我知道我可以通过使用单独的目录或在 DirectoryCatalog 上使用搜索过滤器来绕过它,但我想要一种更通用的方法来解决问题。有什么方法可以处理异常并允许合成继续吗?或者还有其他更通用的解决方案吗?

最佳答案

为了避免其他人编写他们自己的 SafeDirectoryCatalog 实现,这是我根据 Wim Coenen 的建议想出的一个:

public class SafeDirectoryCatalog : ComposablePartCatalog
{
private readonly AggregateCatalog _catalog;

public SafeDirectoryCatalog(string directory)
{
var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);

_catalog = new AggregateCatalog();

foreach (var file in files)
{
try
{
var asmCat = new AssemblyCatalog(file);

//Force MEF to load the plugin and figure out if there are any exports
// good assemblies will not throw the RTLE exception and can be added to the catalog
if (asmCat.Parts.ToList().Count > 0)
_catalog.Catalogs.Add(asmCat);
}
catch (ReflectionTypeLoadException)
{
}
catch (BadImageFormatException)
{
}
}
}
public override IQueryable<ComposablePartDefinition> Parts
{
get { return _catalog.Parts; }
}
}

关于c# - 在 MEF 组合期间处理 ReflectionTypeLoadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4144683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com