Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Code Compilation in .Net Core 2.1

Has anyone managed to find a workaround/way to dynamically compile a file, or files, or text, into a .dll in .Net Core (2.1)?

        var csProvider = CodeDomProvider.CreateProvider("CSharp");
        CompilerResults compilerResults = csProvider.CompileAssemblyFromFile(options, files); 

results in a PlatformNotSupportedException and it seems CodeDom is only of very limited use in .Net Core. See similar complaint and compare view of System.CodeDom.Compiler in .Net Core 2.1 vs .Net Framework 4.7.2.

We need to be able to write and dynamically compile custom code on-site. I have a way of dynamically loading any resultant .dll, but I just need to be able to get that .dll in the first place.

The only workaround I can see at the moment is to create a .Net Framework api/service to do this. Is the only other solution here to give up on .Net Core and go to .Net Framework?

Note: I wanted to do this dynamically within the code base. So the solution for "Is it possible to compile a single C# code file with .net core Roslyn compiler?" is not relevant as it states: "To invoke Roslyn compiler directly it is necessary to use command line driver" which would have set me on completely the wrong path. However "How to compile a C# file with Roslyn programmatically?" would provide the solution if I'd known that that is what I was looking to do.

The link provided by @Sami Kahmonem to Joel Martinez' solution in .Net Core 1 was what I used to solve this problem.

like image 425
monty Avatar asked Oct 16 '22 14:10

monty


1 Answers

There are two options for you.

  1. Use the Roslyn Scripting API (Microsoft.CodeAnalysis.CSharp.Scripting). This is pretty easy and surprisingly fast. Also you do not write any binaries to the file system.

  2. Use the full compiler to create a DLL and load it. I would not recommend doing this if possible.

For detailed explanations you should look at this question: Compiling and Running code at runtime in .Net Core 1.0 (you do not need to create a NuGet.config or anything like this)

like image 131
kaesaecracker Avatar answered Oct 21 '22 00:10

kaesaecracker