Type.GetType 无法从已加载的程序集创建类型
我有一个使用 Asssembly.LoadFrom
方法加载程序集的程序。一段时间后,我尝试使用 Type.GetType
从该程序集创建类型(使用 AssemblyQualifiedName
),但该方法返回 null
。如果我将其设置为抛出异常,它会告诉
无法加载文件或程序集“...” 或其依赖项之一。系统 找不到指定的文件。
但我确信已经加载了完全相同的程序集(它显示在 AppDomain.CurrentDomain.GetAssemblies() 列表中)。
有人知道可能出了什么问题和/或如何解决这个问题吗?
I have program which loads an assembly using Asssembly.LoadFrom
method. Some time later I attempt to use Type.GetType
to create a type from that assembly (using AssemblyQualifiedName
), but the method returns null
. If I set it to throw exception, it tells
Could not load file or assembly '...'
or one of its dependencies. The system
cannot find the file specified.
But I am sure the exact same assembly is already loaded (it shows in the AppDomain.CurrentDomain.GetAssemblies()
list).
Anybody has an idea what could be wrong and/or how to solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了理解为什么这不起作用,您需要理解“加载上下文”的问题。 Type.GetType 只查看“Load”上下文。您加载到内存中的程序集位于“LoadFrom”上下文中。
真正在加载上下文中进行绑定以查看加载源上下文中的程序集的唯一方法是使用 AssemblyResolve 事件并编写代码以返回正确的程序集。 AssemblyResolve 事件在绑定失败且所有其他程序集查找未成功之前触发。
有关加载上下文以及使用 LoadFrom 时出现的问题的更多信息,请参阅以下链接。
MSDN - http://msdn.microsoft.com/en-us/library/ dd153782.aspx
AssemblyResolve - http://msdn.microsoft.com/en- us/library/system.appdomain. assemblyresolve.aspx
苏珊·库克 - 链接
In order to understand why this doesn't work, you need to understand the issue of "load contexts". Type.GetType only looks at the "Load" context. The assembly you loaded into memory was in the "LoadFrom" context.
The only way to really get binds in the load context to see assemblies in the load-from context is to use the AssemblyResolve event and write code to return the correct assembly. The AssemblyResolve event fires right before the bind fails and all other assembly lookup did not succeed.
See the following links for more information about load contexts and issues that arise when using LoadFrom.
MSDN - http://msdn.microsoft.com/en-us/library/dd153782.aspx
AssemblyResolve - http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx
Suzanne Cook - Link
如果您可以使用 Assembly.LoadFrom 获取程序集,那么您可以通过执行以下操作来获取类型:
assembly.GetType 还有其他重载,您可以了解此处
If you can get the assembly using Assembly.LoadFrom then you can get the type by doing:
The assembly.GetType has other overloads which you can find out about here