C# Scripting with Microsoft Roslyn
If you’re not familiar with Microsoft “Roslyn” please read Interactive C# Microsoft Roslyn.
[TestFixture]public class TestScript{[Test]public void TestSimple(){var engine = new ScriptEngine();
Console.WriteLine(engine.Execute("1+1"));
Console.WriteLine(engine.Execute<int>("1+1"));}[Test]public void TestSession(){var engine = new ScriptEngine();
var session = Session.Create();engine.Execute("int x = 1, y;", session);
engine.Execute("if(x==1)y = 10; else y = 20;",session);
Console.WriteLine(engine.Execute("y", session));
}[Test]public void TestScriptFile(){var engine = new ScriptEngine();
ScriptContext context = new ScriptContext();
engine.ExecuteFile("Test.csx", context);
}[Test]public void TestScriptFileHostObject(){var context = new ScriptContext();
var engine = new ScriptEngine(new[] { context.GetType().Assembly.Location });var session = Session.Create(context);context.Name = "Tom";
context.Parameters.Add("Input", "Hello");engine.ExecuteFile("TestHost.csx", session);
Console.WriteLine(context.Parameters["Output"]);
}}public class ScriptContext{public Dictionary<string, object> Parameters { get; set; }public string Name { get; set; }public ScriptContext()
{Parameters = new Dictionary<string, object>();}}
Test.csx
using System;
var hello = "Hello";
Console.WriteLine(hello);
TestHost.csx
using System;
var output = string.Format("{0} {1}",Parameters["Input"], Name);Parameters.Add("Output", output);
You can read more on the subject here Introduction to the Roslyn Scripting API
Comments
Post a Comment