6

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.

monty
  • 1,543
  • 14
  • 30

1 Answers1

3

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)

  • How can u create a C# project using those Roslyn APIs? – DioBrando Mar 22 '20 at 19:45
  • @DioBrando If you mean something like a template for `dotnet new` take a look at https://learn.microsoft.com/en-us/dotnet/core/tutorials/cli-templates-create-item-template – kaesaecracker Mar 25 '20 at 12:25
  • To anyone turned off or intimidated at the mention of the word Roslyn, just know that if you have already written code that would work with `CodeDomProvider`, then you have very little work left to do to convert it to something Roslyn can consume. The link provided here has example source code that should make it pretty easy to see how to convert (or at least, it was for me. Perhaps I just had a very simple case, but I suspect most projects will be simple like mine was) – David Aug 23 '21 at 22:16