简体   繁体   English

C#Assembly.Load与参考dll

[英]C# Assembly.Load with reference dlls

I am using the following code to load dlls at run time, and store their classes for later use. 我正在使用以下代码在运行时加载dll,并存储其类供以后使用。

public LoadDll(byte[] data)
{
    Assembly loadedAssembly = Assembly.Load(data);
    System.Type[] types = loadedAssembly.GetTypes();
    TypeRepo.Register(types);
}

and this works great, but if the dll I built has reference to another dll I get the error "The classes in the module cannot be loaded." 并且效果很好,但是如果我构建的dll引用了另一个dll,则会收到错误消息“模块中的类无法加载”。 when calling GetTypes(). 调用GetTypes()时。

How can I provide a specific file path to allow the loaded assembly accesses to a dependency on disk? 如何提供特定的文件路径以允许已加载的程序集访问磁盘上的依赖项?

You should play with AppDomain.AssemblyResolve event 您应该玩AppDomain.AssemblyResolve事件

See what remarks section of the linked documentation points out: 请参阅链接文档的备注部分指出:

It is the responsibility of the ResolveEventHandler for this event to return the assembly that is specified by the ResolveEventArgs.Name property, or to return null if the assembly is not recognized. 此事件的ResolveEventHandler负责返回由ResolveEventArgs.Name属性指定的程序集,如果未识别该程序集,则返回null。 The assembly must be loaded into an execution context; 程序集必须加载到执行上下文中。 if it is loaded into the reflection-only context, the load that caused this event to be raised fails. 如果将它加载到仅反射上下文中,则导致引发此事件的加载失败。

So you need to perform an Assembly.LoadFrom to return the whole Assembly instance by loading satellite assemblies from an arbitrary path defined by you in code. 因此,您需要执行Assembly.LoadFrom以通过从代码中由您定义的任意路径加载附属程序集来返回整个Assembly实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM