Search code examples
c#.net.net-assemblycodedomcsharpcodeprovider

Rreference run-time compiled assembly in other run-time compiled assembly


I'm trying to compile code at runtime that is referenced by an object that is also compiled at run-time in C# .NET 4.6.

I'm using CSharpCodeProvider to generate a CompilerResult in memory. The resulting assembly is referenced in the 2nd code fragment that is compiled. Is it possible to add the AssemblyReference to the CompilerParameters before I compile the 2nd piece (otherwise I'd get a missing assembly compiler error).

Currently I see two options:

  1. Create the 1st assembly on disc and use CompilerParameters.ReferencedAssemblies.Add (But I don't like unnecessary disc operations)
  2. Do not generate the 1st piece at all but paste the code in the 2nd piece (But I don't like to paste the same code many times)

So my question: Is there an in-memory way to reference a run-time generated assembly in another run-time generated assembly?


Solution

  • CSharpCodeProvider works on a disk anyway - even when you only generate the assembly "in-memory", it compiles the assembly on disk and loads it to memory (it has to, kind of - all it does is call csc.exe). The only difference is that the assembly file is a temporary DLL somewhere, rather than a file you specified.

    If you want true in-memory compilation of C# code, use the Roslyn compiler.