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