简体   繁体   English

.Net Core 2.1中的动态代码编译

[英]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)? 是否有人设法找到一种解决方法/方式将一个或多个文件动态编译为.Net Core(2.1)中的.dll?

        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. 会导致PlatformNotSupportedException,并且看来CodeDom在.Net Core中的用途非常有限。 See similar complaint and compare view of System.CodeDom.Compiler in .Net Core 2.1 vs .Net Framework 4.7.2 . 参见类似的投诉,并比较.Net Core 2.1.Net Framework 4.7.2中System.CodeDom.Compiler的视图。

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. 我有一种动态加载任何生成的.dll的方法,但是我只需要能够首先获取该.dll。

The only workaround I can see at the moment is to create a .Net Framework api/service to do this. 我目前只能看到的解决方法是创建一个.Net Framework api / service来执行此操作。 Is the only other solution here to give up on .Net Core and go to .Net Framework? 是这里唯一放弃使用.Net Core并转到.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?" 因此解决方案“是否可以使用.net核心Roslyn编译器编译单个C#代码文件?” 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. 它与状态无关,因为它指出:“要直接调用Roslyn编译器,必须使用命令行驱动程序”,这会使我走上完全错误的道路。 However "How to compile a C# file with Roslyn programmatically?" 但是, “如何使用Roslyn以编程方式编译C#文件?” 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. @Sami Kahmonem提供的指向.Net Core 1中Joel Martinez解决方案的链接是我用来解决此问题的方法。

There are two options for you. 有两个选项供您选择。

  1. Use the Roslyn Scripting API (Microsoft.CodeAnalysis.CSharp.Scripting). 使用Roslyn脚本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. 使用完整的编译器创建DLL并加载它。 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) 有关详细的解释,您应该查看以下问题: .Net Core 1.0中的运行时编译和运行代码 (无需创建NuGet.config或类似的内容)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM