Roslyn / CSharpScript - How to save / load compilation to avoid compile timeout

I am trying to integrate C # scripts in my database application. I use the globals object to get global variables from a script.

I am not happy with the wait time if the script is compiled for the first time.
How to save and load compilation to avoid waiting time?

Script<object> script = CSharpScript.Create(scriptCode, globalsType: typeof(MyGlobals));
script.Compile();   //<-- load the Compilation from database/file here
script.RunAsync(myGlobalsInstance).Wait();
+4
source share
2 answers

You can create CSharpScript and then get the compilation through GetCompilationto get the compilation.

var script = CSharpScript.Create("script..");
var compilation = script.GetCompilation();

compilation.Emit() dll pdb . ( roslyn) - , , . , roslyn .

+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 no errors in the results.Errors

. , . , script, . :

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);

, , . . classInstance.ExecuteSomething(...)

-1

Source: https://habr.com/ru/post/1654441/


All Articles