2

我正在使用基于的脚本规则引擎,它将处理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));

这里有几个问题:

  • 不支持dynamic关键字
  • 在脚本中使用匿名类型Duplicate type name within an assembly时,当使用创建程序集时出现异常System.Reflection.Emit

问题

当脚本包含匿名类型时,有没有办法ScriptEngine多次创建和重用它?

4

1 回答 1

2

你在 Roslyn 中遇到了一个错误。

我建议不要循环编译脚本。由于代码不会更改,因此仅更新脚本正在使用的数据会更有效。这种方法也避免了该错误。

var model = new Model();
var session = engine.CreateSession(model);
var submission = session.CompileSubmission<dynamic>(script);
foreach (Model data in models)
{
    model.InputA = data.InputA;
    model.InputB = data.InputB;
    model.Factor = data.Factor;

    dynamic result = submission.Execute();
    Console.WriteLine("{0} {1} {2}", result.Σ, result.Δ, result.λ);
}
于 2013-03-19T20:44:24.730 回答