.Net Core 1.0中的运行时编译和运行代码
是否可以在新的.Net Core(更好的.Net Standard Platform)中在运行时编译和运行C#代码?我已经看到了一些示例(.Net Framework),但是它们使用了与netcoreapp1.0(.NETCoreApp,Version = v1.0)不兼容的NuGet软件包
Is it possible to compile and run C# code at runtime in the new .Net Core (better .Net Standard Platform)? I have seen some examples (.Net Framework), but they used NuGet packages that are not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0)
选项#1 :使用完整的C#编译器编译程序集,加载程序集,然后从中执行方法。
Option #1: Use the full C# compiler to compile an assembly, load it and then execute a method from it.
这需要以下软件包作为project.json中的依赖项:
This requires the following packages as dependencies in your project.json:
"Microsoft.CodeAnalysis.CSharp": "1.3.0-beta1-20160429-01",
"System.Runtime.Loader": "4.0.0-rc2-24027",
然后您可以使用如下代码:
Then you can use code like this:
var compilation = CSharpCompilation.Create("a")
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location))
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(
@"
using System;
public static class C
{
public static void M()
{
Console.WriteLine(""Hello Roslyn."");
}
}"));
var fileName = "a.dll";
compilation.Emit(fileName);
var a = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(fileName));
a.GetType("C").GetMethod("M").Invoke(null, null);
选项#2 :使用Roslyn脚本,这将导致更简单的代码,但当前需要更多设置:
Option #2: Use Roslyn Scripting. This will result in much simpler code, but currently requires more setup:
-
创建NuGet.config可以从Roslyn夜间供稿中获取软件包:
p>
Create NuGet.config to get packages from the Roslyn nightly feed:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="Roslyn Nightly" value="https://www.myget.org/F/roslyn-nightly/api/v3/index.json" />
</packageSources>
</configuration>
将以下软件包作为依赖项添加到project.json(注意,这是从今天开始的软件包,您需要ent版本):
Add the following package as a dependency to project.json (notice that this is package from today, you will need different version in the future):
"Microsoft.CodeAnalysis.CSharp.Scripting": "1.3.0-beta1-20160530-01",
您还需要导入 dotnet
(已过时的 Target Framework Moniker,尽管如此,罗斯林仍然使用):
You also need to import dotnet
(obsolete "Target Framework Moniker", which is nevertheless still used by Roslyn):
"frameworks": {
"netcoreapp1.0": {
"imports": "dotnet5.6"
}
}
现在您终于可以使用脚本了:
Now you can finally use Scripting:
CSharpScript.EvaluateAsync(@"using System;Console.WriteLine(""Hello Roslyn."");").Wait();