RulesEngine,你值得拥有

使用非常简单,你只需要安装nuget包

<PackageReference Include="RulesEngine" Version="6.0.0" />
  1. 创建工作流

也可以从json加载

var workflow = new Workflow[]
{
    new Workflow
    {
        WorkflowName = "Discount",
        RuleExpressionType = RuleExpressionType.LambdaExpression,
        Rules = new Rule[]
        {
            new Rule
            {
                RuleName = "IsCustomerEligibleForDiscount",
                Expression = "input1.Age >= 18 && input1.PurchaseAmount > 1000",
                SuccessEvent = "Customer is eligible for discount.",
                ErrorMessage = "Customer is not eligible for discount.",
                Enabled = true
            }
        }
    }
};
  1. 初始化引擎
var rulesEngine = new RulesEngine.RulesEngine(workflow);
  1. 执行规则

执行规则有两个方法,ExecuteActionWorkflowAsyncExecuteAllRulesAsync,我平常用ExecuteActionWorkflowAsync完全足够

ExecuteActionWorkflowAsync

ExecuteActionWorkflowAsync需要注意的是规则字符串Expression中变量不能带’.’(点符号),只支持1个input,不需要input1.xx

var res = await rulesEngine.ExecuteActionWorkflowAsync("Discount", "IsCustomerEligibleForDiscount", new RuleParameter[] { new("Age", 18), new("PurchaseAmount", 1500) });

foreach (var item in res.Results)
{
    Console.WriteLine($"规则: {item.Rule.RuleName}");
    Console.WriteLine($"是否成功: {item.IsSuccess}");
    Console.WriteLine($"消息: {item.Rule.ErrorMessage}");
}

ExecuteAllRulesAsync

支持多个input,必须使用input1.xx,其中input1标识input第1个参数;如下示例,你不用管参数input2,input3变量命名,你可以随便命名,input对象CustomerInput也是自定义(保证对象有对应参数),表达式中input1取的是input2,第1个传入参数

var input2 = new CustomerInput
{
    Age = 18,
    PurchaseAmount = 1500
};
var input3 = new CustomerInput
{
    Age = 5,
    PurchaseAmount = 1500
};
var res = await rulesEngine.ExecuteAllRulesAsync("Discount", input2, input3);
foreach (var item in res)
{
    Console.WriteLine($"规则: {item.Rule.RuleName}");
    Console.WriteLine($"是否成功: {item.IsSuccess}");
    Console.WriteLine($"消息: {item.Rule.ErrorMessage}");
}