I have installed Microsoft.CodeAnalysis.CSharp & Microsoft.CodeAnalysis.CSharp.Scripting (Version 3.3.1) packages in the .Net Core 2.2 Console Application and also I have developed the codes below :
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
public class MyGlobals
{
public int Age {get; set;} = 21;
}
");
var references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
};
var compilation = CSharpCompilation.Create("DynamicAssembly")
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddSyntaxTrees(syntaxTree)
.AddReferences(references);
Type globalsType = null;
Assembly assembly = null;
using (var memoryStream = new MemoryStream())
{
var compileResult = compilation.Emit(memoryStream);
assembly = Assembly.Load(memoryStream.GetBuffer());
if (compileResult.Success)
{
globalsType = assembly.GetType("MyGlobals");
}
}
var globals = Activator.CreateInstance(globalsType);
var validationResult = CSharpScript.EvaluateAsync<bool>("Age == 21", globals: globals);
The globals object is created but the expression is not evaluated and the following exception is throwed by CSharpScript :
The name 'Age' does not exist in the current context (are you missing a reference to assembly 'DynamicAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'?)'
Is there a setting I missed?
globals
variable is of type object. You probably need to cast it toMyGlobals
type. – dropoutcoderdynamic globals = Activator.CreateInstance(globalsType);
– dropoutcoder