我正在运行时编译动态程序集。它需要引用另一个 dll。一切正常,只要我在 CompilerParameters 中设置 OutputAssembly。但是一旦我设置 GenerateInMemory = true;它失败了:
var compilerParameters = new CompilerParameters();
if( compileInMemory )
compilerParameters.GenerateInMemory = true;
else
compilerParameters.OutputAssembly = "<my_dynamic_dll_path>";
compilerParameters.ReferencedAssemblies.Add( "<other_dll_path>" );
var compilerResults = new CSharpCodeProvider().CompileAssemblyFromDom( compilerParameters, codeCompileUnit );
// Here: compilerResults.Errors.HasErrors == false
foreach( var type in compilerResults.CompiledAssembly.GetTypes() )
{
// Exception:
// Unable to load one or more of the requested types.
// Retrieve the LoaderExceptions property for more information.
}
LoaderExceptions 告诉我找不到“other_dll”。为什么只要我不在内存中编译它就可以工作,我必须做什么才能让它在内存中工作?
最佳答案
使用 GenerateInMemory 时没有加载上下文,程序集由 Assembly.Load(Byte[]) 重载加载。一种解决方法是临时 Hook AppDomain.AssemblyResolve 事件,以便您可以自己加载“other_dll”。
关于c# - 当 CompilerParameters.GenerateInMemory == true 时,在运行时编译类失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/591806/