Roslyn / CSharpScript-如何保存/加载编译以避免编译等待时间

Bog*_*mil 5 c# scripting roslyn

我正在尝试将c#脚本集成到我的数据库应用程序中。我正在使用globals对象来使全局变量可从脚本访问。

如果脚本是第一次编译,我对等待时间不满意。
如何保存和加载编译以避免等待时间?

Script<object> script = CSharpScript.Create(scriptCode, globalsType: typeof(MyGlobals));
script.Compile();   //<-- load the Compilation from database/file here
script.RunAsync(myGlobalsInstance).Wait();
Run Code Online (Sandbox Code Playgroud)

小智 -1

如果你想预编译,你可以使用 System.CodeDom.Compiler 中的类;

CompilerParameters opts = new CompilerParameters();

opts.OutputAssembly = <Destination FileName>;
opts.ReferencedAssemblies.AddRange(<needed references>);
//set other options;            

var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
var results = codeProvider.CompileAssemblyFromFile(opts, <Your script source files>);
//check that there's no errors in the results.Errors
Run Code Online (Sandbox Code Playgroud)

现在磁盘上已经有了一个编译好的程序集。您可以动态加载它,从中实例化一个类并执行方法。您应该设计在脚本中运行的代码,使其接受某些配置。您应该采取以下步骤:

var mydll =  AppDomain.CurrentDomain.Load(<compiled Assembly From the previous step>);
    var classInstance =  <YouTypeOrInterface>mydll.CreateInstance(
      <TypeFromTheAssembly>, 
      false, 
      BindingFlags.CreateInstance, 
      null,                                                                
      new object[] { <Arguments you need to provides to your class constructor> },                                                                              CultureInfo.InvariantCulture, null);
Run Code Online (Sandbox Code Playgroud)

现在您可以使用此实例执行您想要的操作。例如 classInstance.ExecuteSomething(...)