I have an application in which I use the Roslyn scripting engine (namespace Microsoft.CodeAnalysis.Scripting
).
What I have right now is this:
public static async Task<object> Execute(string code, CommandEventArgs e)
{
if (_scriptState == null)
{
var options = ScriptOptions.Default;
options
.AddReferences(typeof (Type).Assembly,
typeof (Console).Assembly,
typeof (IEnumerable<>).Assembly,
typeof (IQueryable).Assembly)
.AddImports("System", "System.Numerics", "System.Text", "System.Linq", "System.Collections.Generics",
"System.Security.Cryptography");
_scriptState = await CSharpScript.RunAsync(code, options, new MessageGlobal {e = e});
}
else
{
// TODO: set global e (it's not in this variables list, thus it throws null reference)
_scriptState.GetVariable("e").Value = e;
_scriptState = await _scriptState.ContinueWithAsync(code);
}
return !string.IsNullOrEmpty(_scriptState.ReturnValue?.ToString()) ? _scriptState.ReturnValue : null;
}
To make it more clear: In my app, there is a certain event. User can define what happens when the event occurs with some C# code (this code is being changed frequently). Now the point is - I need to pass event args to the script, so the user can use it in the code. In the same time, I need to keep the engine state, since the user could have defined some variables, which he wants to use the next time.
I already can pass the event args (and refer to it like e
in the script), but only for the first time (i.e. when the ScriptState
is null and I create a new one). The next time this or some other script is ran (ScriptState.ContinueWithAsync
), the event args are the same as in the previous state, because I don't know any way to update them.
How can I reach the e
global and set it to a new value? I've already tried to access it (as you can see in the code) through the Variables
list, but it seems that globals aren't kept in the list. At the same time I can't add any variable when running the first script, because the ScriptVariable
class has an internal constructor. (ScriptState.Variables.Add( ScriptVariable )
)
Thanks for the help. I hope I've articulated myself, be sure to ask anything in comments.