【问题标题】:Getting information from an Assembly without loading it从程序集中获取信息而不加载它
【发布时间】:2013-03-12 17:38:45
【问题描述】:

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

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

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

编辑:

我引用了 Mono.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

【问题讨论】:

  • 为什么提供这两个选项?只是好奇...
  • 目前主要是遗留问题。我希望能够从远程位置加载 dll,并且出于某种原因需要从磁盘加载某些 dll。我希望将其作为一个选项删除,并根据每个 dll 决定什么是最好的,但我希望我的开发人员能够控制发生的事情。

标签: .net reflection .net-assembly


【解决方案1】:

仅反射加载仍然会加载事物,所以一旦你这样做了,再问这个问题就太晚了。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2011-02-12
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多