Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling a class at runtime failes when CompilerParameters.GenerateInMemory == true

Tags:

c#

reflection

I am compiling a dynamic assembly at runtime. It needs to reference another dll. Everything works alright, as long as I set an OutputAssembly in my CompilerParameters. But as soon as I set GenerateInMemory = true; it fails:

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.
}

The LoaderExceptions are telling me that "other_dll" could not be found. Why is it working as long as I do not compile in-memory and what do I have to do to make it working in-memory?

like image 853
tanascius Avatar asked Feb 26 '09 18:02

tanascius


1 Answers

There is no loading context when you use GenerateInMemory, the assembly gets loaded by the Assembly.Load(Byte[]) overload. One workaround is to temporarily hook the AppDomain.AssemblyResolve event so you can load "other_dll" yourself.

like image 58
Hans Passant Avatar answered Oct 20 '22 15:10

Hans Passant