我的应用程序有一个插件结构,它将 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/