我正在使用基于roslyn-ctp的脚本规则引擎,它将处理IEnumerable<T>
并返回结果为IEnumerable<T>
. 为了避免ScriptEngine
一次又一次地创建、配置和解析,我想重用一个ScriptEngine
.
这是一个简短的示例(gist.github.com上的完整示例):
var engine = new ScriptEngine();
new[]
{
typeof (Math).Assembly,
this.GetType().Assembly
}.ToList().ForEach(assembly => engine.AddReference(assembly));
new[]
{
"System", "System.Math",
typeof(Model.ProcessingModel).Namespace
} .ToList().ForEach(@namespace => engine.ImportNamespace(@namespace));
IEnumerable<Model.ProcessingModel> models = new[]
{
new Model.ProcessingModel { InputA = 10M, InputB = 5M, Factor = 0.050M },
new Model.ProcessingModel { InputA = 20M, InputB = 2M, Factor = 0.020M },
new Model.ProcessingModel { InputA = 12M, InputB = 3M, Factor = 0.075M }
};
// no dynamic allowed
// anonymous class are duplicated in assembly
var script =
@"
Result = InputA + InputB * Factor;
Delta = Math.Abs((Result ?? 0M) - InputA);
Description = ""Some description"";
var result = new { Σ = Result, Δ = Delta, λ = Description };
result
";
// Here is ArgumentException `Duplicate type name within an assembly`
IEnumerable<dynamic> results =
models.Select(model => engine.CreateSession(model).Execute(script));
这里有几个问题:
- roslyn-ctp不支持
dynamic
关键字 - 在脚本中使用匿名类型
Duplicate type name within an assembly
时,当rsolyn-ctp使用创建程序集时出现异常System.Reflection.Emit
问题
当脚本包含匿名类型时,有没有办法ScriptEngine
多次创建和重用它?