C# Assembly.Load 带有引用 dll
C# Assembly.Load with reference dlls
我正在使用以下代码在 运行 时加载 dll,并存储它们 类 以备后用。
public LoadDll(byte[] data)
{
Assembly loadedAssembly = Assembly.Load(data);
System.Type[] types = loadedAssembly.GetTypes();
TypeRepo.Register(types);
}
这很好用,但是如果我构建的 dll 引用了另一个 dll,我在调用 GetTypes() 时会收到错误 "The classes in the module cannot be loaded."。
如何提供特定的文件路径以允许加载的程序集访问磁盘上的依赖项?
你应该玩AppDomain.AssemblyResolve event
查看链接文档的 备注 部分指出的内容:
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. 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.
因此您需要通过从您在代码中定义的任意路径加载附属程序集来执行 Assembly.LoadFrom
到 return 整个 Assembly
实例。
我正在使用以下代码在 运行 时加载 dll,并存储它们 类 以备后用。
public LoadDll(byte[] data)
{
Assembly loadedAssembly = Assembly.Load(data);
System.Type[] types = loadedAssembly.GetTypes();
TypeRepo.Register(types);
}
这很好用,但是如果我构建的 dll 引用了另一个 dll,我在调用 GetTypes() 时会收到错误 "The classes in the module cannot be loaded."。
如何提供特定的文件路径以允许加载的程序集访问磁盘上的依赖项?
你应该玩AppDomain.AssemblyResolve event
查看链接文档的 备注 部分指出的内容:
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. 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.
因此您需要通过从您在代码中定义的任意路径加载附属程序集来执行 Assembly.LoadFrom
到 return 整个 Assembly
实例。