.net - 从程序集中获取信息而不加载它

标签 .net reflection .net-assembly

我的应用程序有一个插件结构,它将 dll(沼泽标准 .NET 程序集)作为插件加载。我有一个应用程序范围的选项,可以直接从磁盘加载这些 dll (Assembly.LoadFrom(file)) 或先将 dll 复制到内存中,然后从字节数组加载 ( Assembly.Load(IO.File.ReadAllBytes(文件)))。

我想为插件开发者添加一个选项,让他们选择是否要强制执行特定的加载行为。我想我会为此使用 AssemblyAttributes,然后 ReflectionOnly 加载 dll 以查看是否定义了该属性。但是,我无法使用 GetCustomAttributesData 获取此信息,因为 dll 依赖于其他尚未加载的程序集。我现在发现自己置身于卡夫卡式的打地鼠游戏中。

插件开发人员在真正加载他们的 dll 之前与我的应用程序通信的好方法是什么? AssemblyAttributes 是可行的方法吗?如果是,我如何确保仅反射加载永远不会失败?

编辑:

我引用了 Mono.Cecil 来迭代程序集属性。我第一次使用 Cecil,希望我做对了。在我的开发机器上进行的初始测试似乎有效。

Private Function ExtractAssemblyLoadBehaviour(ByVal file As String) As GH_LoadingBehaviour
  Try
    If (Not IO.File.Exists(file)) Then Return GH_LoadingBehaviour.ApplicationDefault

    Dim assembly As AssemblyDefinition = AssemblyDefinition.ReadAssembly(file)
    If (assembly Is Nothing) Then Return GH_LoadingBehaviour.ApplicationDefault

    Dim attributes As Collection(Of CustomAttribute) = assembly.CustomAttributes
    If (attributes Is Nothing) Then Return GH_LoadingBehaviour.ApplicationDefault
    For Each Attribute As CustomAttribute In attributes
      Dim type As TypeReference = Attribute.AttributeType
      If (type.FullName.Contains("GH_CoffLoadingAttribute")) Then Return GH_LoadingBehaviour.ForceCOFF
      If (type.FullName.Contains("GH_DirectLoadingAttribute")) Then Return GH_LoadingBehaviour.ForceDirect
    Next

    Return GH_LoadingBehaviour.ApplicationDefault
  Catch ex As Exception
    Return GH_LoadingBehaviour.ApplicationDefault
  End Try
End Function

最佳答案

Reflection-only load 仍然加载这个东西,所以一旦你这样做了,再问这个问题就太晚了。

一个选择是在单独的 AppDomain 中执行仅反射加载,然后将结果返回到您的主代码,并丢弃新的 AppDomain。

使用属性的替代方法是要求插件开发人员包含某种 list 文件(例如文本或 XML),其中包含您需要的任何信息或选项。

关于.net - 从程序集中获取信息而不加载它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15368237/

相关文章:

C# - 在字符串列表列表中重复而不是正确的值

c# - 在 C# 中冒泡排序最优雅的方法是什么?

c# - 使用反射 c# 实现接口(interface)

c# - 以编程方式获取转换和输出运算符类型

.net - Azure Devops Pipeline NuGetCommand 不断失败

c# - .ToUniversalTime(),为什么会这样?

c# - 通过反射转换到泛型接口(interface)

c++ - 在非托管程序中托管 CLR 时从内存加载程序集

c# - 如何在Windows phone 8 中通过Assembly.Load 动态加载程序集?

c# - 从 IL 创建方法的副本