Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object instance to Roslyn ScriptEngine

Tags:

c#

.net

roslyn

I'm looking for a C# scripting engine, that can interpret blocks of C# code, while maintaing a context. For example, if enter to it: var a = 1; , and then a + 3, it'll output 4. I'm aware of MS Roslyn , which indeed do that, but it's a sandbox (respect to the program that launched it). So, if I create an instance of ScriptEngine and an instance of MyClass (just an arbirary class of mine) , I have no option to pass a reference of my_class to script_engine.

Is it possible to somehow pass that reference?

What I'd like to do, is something like:

ScriptEngine engine; // A Roslyn object
Session session // A Roslyn object

MyClass my_class; // My object

// all required initializations

Submission<object> sm = session.CompileSubmission<object>("var a=1;"); 
dynamic result = sm.Execute(); 

Submission<object> sm = session.CompileSubmission<object>("a + 3;"); 
dynamic result = sm.Execute(); // result is now 4

MyClass my_class;
session.AddReferenceToAnOject(my_class); // function that does not exists, but reflect my intention

Submission<object> sm = session.CompileSubmission<object>("my_class.ToString();"); 
dynamic result = sm.Execute();  // result is no the output of my_class.ToString()

Please notice that AddReferenceToAnOject() is the missing part, as there's no such function in roslyn.

like image 955
MarkSh Avatar asked Jul 14 '14 09:07

MarkSh


1 Answers

The answer was found in a link commented by @Herman.

As it turn out, Roslyn ScriptEngine/Session supports a concept of Host Object. In order to use it, define a class of your choise, and pass it upon session creation. Doing so, makes all public member of that host object, available to context inside the session:

public class MyHostObject
{
    public List<int> list_of_ints;
    public int an_int = 23;
}

var hostObject = new MyHostObject();
hostObject.list_of_ints = new List<int>();
hostObject.list_of_ints.Add(2);
var engine = new ScriptEngine(new[] { hostObject.GetType().Assembly.Location });

// passing reference to hostObject upon session creation
var session = Session.Create(hostObject);

// prints `24` to console
engine.Execute(@"System.Console.WriteLine(an_int + list_of_ints.Count);", 
               session); 
like image 185
MarkSh Avatar answered Nov 10 '22 15:11

MarkSh