【问题标题】:Why is AssemblyResolve event trying to resolve an assembly that is already loaded in the AppDomain?为什么 AssemblyResolve 事件试图解析 AppDomain 中已加载的程序集?
【发布时间】:2016-12-20 16:39:39
【问题描述】:

我有一项服务,它涉及从云存储下载程序集,使用 Activator.CreateInstance 创建它的实例,然后在其上调用方法。

我已经设置了一个 AssemblyResolve 方法来下载运行良好的依赖项,但是为了测试/实验,我现在正在尝试手动下载程序集。我已经找到需要哪些依赖项,下载它们,然后使用加载它们

Assembly.Load(byte[])

之后我可以看到它们通过

加载到 AppDomain
AppDomain.CurrentDomain.GetAssemblies())

但是,当我在引用它的程序集上调用方法时,它仍然会转到 AssemblyResolver。

我可能误解了加载的程序集和 AppDomain 的工作原理,但在我看来,一旦加载了程序集,它就应该可供该程序集使用并且不需要解决它?

为什么它不能“看到”它?版本名称等都是一样的。

我已经阅读了不同的程序集绑定上下文here,我认为这可能是问题所在?它表明使用 Assembly.Load(string) 将加载到与 Assembly.Load(byte) 不同的上下文?在这种情况下,当我将程序集作为字节 [] 保存在内存中时,我该怎么做?

谢谢

【问题讨论】:

  • 即使你已经使用了Assembly.Load(..),它是否加载程序集失败?
  • 你能在 Visual Studio 中显示你的Debug->Widnows->Modules 屏幕截图吗?
  • 请添加显示您如何加载类型、获取方法并执行它的代码。我已经对问题所在进行了有根据的猜测;-)
  • @Redhead 没有错误,因为它只会通过 AssemblyResolve 事件解决依赖关系,我想知道为什么它不能只使用我已经手动加载的程序集,我可以看到在 AppDomain.GetAssemblies() 中

标签: c# .net .net-assembly assembly-resolution


【解决方案1】:

您需要直接从您加载的程序集中获取类型,因为它没有加载到正确的上下文中。

var assembly = Assembly.Load(File.ReadAllBytes(some_path));

// This will work. Note that you don't need the assembly-qualified name,
// as you are asking the assembly directly for the type.
var type1 = assembly.GetType("My.Special.Type");

// This will not work - the assembly "My.Assembly" is not loaded into
// the Load context, so the type is not available.
var type2 = Type.GetType("My.Special.Type, My.Assembly");

在上面的代码中,type1 将引用类型,但type2 将为空,因为程序集未加载到正常的加载上下文中。

【讨论】:

  • 这就是我们对实际运行的程序集所做的事情,问题是我用 Assembly.Load(byte[]) 加载的依赖项显然不能使用,所以当我运行该方法时即使它想要的程序集已经加载到 AppDomain 中,它也会从该类型触发 AssemblyResolve 事件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2023-04-08
  • 2021-05-11
  • 1970-01-01
  • 2010-11-12
  • 2011-03-02
  • 1970-01-01
相关资源
最近更新 更多