Table of Contents

Nested rules and scoped parameters

This tutorial builds on Your first workflow. You will make rules easier to read with scoped parameters, and combine rules with nested And/Or rules.

The workflow

An order has a country, a total and a list of items. Save this as order.json:

[
  {
    "WorkflowName": "Order",
    "GlobalParams": [
      { "Name": "isDomestic", "Expression": "order.country == \"india\"" },
      { "Name": "itemCount", "Expression": "order.items.Count()" }
    ],
    "Rules": [
      {
        "RuleName": "BulkDomestic",
        "LocalParams": [
          { "Name": "averagePrice", "Expression": "order.total / itemCount" }
        ],
        "Expression": "isDomestic AND itemCount >= 3 AND averagePrice >= 100"
      },
      {
        "RuleName": "AnyBigSignal",
        "Operator": "OrElse",
        "Rules": [
          { "RuleName": "ManyItems", "Expression": "itemCount >= 3" },
          { "RuleName": "BigOrder", "Expression": "order.total >= 1000" }
        ]
      }
    ]
  }
]

Global parameters

GlobalParams belong to the workflow and are visible to every rule. Each one is an expression with a name, like a var in C#. They are evaluated once per call to ExecuteAllRulesAsync, not once per rule, so they are a good place for work that several rules need. A global can use the inputs and the globals before it.

Local parameters

LocalParams belong to one rule (and its child rules). averagePrice above uses the global itemCount, which shows that scoped parameters can build on each other.

Nested rules

A rule with an Operator and child Rules has no Expression of its own. Its result is computed from its children:

Operator The parent passes when
And or AndAlso every child passes
Or or OrElse at least one child passes

Run it

using System.Text.Json;
using RulesEngine.Models;

var workflows = JsonSerializer.Deserialize<Workflow[]>(File.ReadAllText("order.json"));
var order = new
{
    country = "india",
    total = 450,
    items = new[] { new { Name = "pen" }, new { Name = "book" }, new { Name = "bag" } }
};

foreach (var mode in new[] { NestedRuleExecutionMode.All, NestedRuleExecutionMode.Performance })
{
    var engine = new RulesEngine.RulesEngine(workflows, new ReSettings { NestedRuleExecutionMode = mode });
    var results = await engine.ExecuteAllRulesAsync("Order", new RuleParameter("order", order));

    Console.WriteLine($"Mode: {mode}");
    foreach (var result in results)
    {
        Console.WriteLine($"  {result.Rule.RuleName}: {result.IsSuccess}");
        foreach (var child in result.ChildResults ?? Enumerable.Empty<RuleResultTree>())
        {
            Console.WriteLine($"    {child.Rule.RuleName}: {child.IsSuccess}");
        }
    }

    // Scoped parameters appear in the inputs of every result.
    Console.WriteLine($"  inputs of the first result: {string.Join(", ", results[0].Inputs.Keys)}");
}

Expected output:

Mode: All
  BulkDomestic: True
  AnyBigSignal: True
    ManyItems: True
    BigOrder: False
  inputs of the first result: order, isDomestic, itemCount, averagePrice
Mode: Performance
  BulkDomestic: True
  AnyBigSignal: True
    ManyItems: True
  inputs of the first result: order, isDomestic, itemCount, averagePrice

What to notice

  • AnyBigSignal passes because ManyItems passes, even though BigOrder fails.
  • With NestedRuleExecutionMode.All (the default) both children are evaluated and returned in ChildResults. With Performance the engine stops as soon as the outcome is decided, so BigOrder is never evaluated. Put the cheapest or most likely child first when you use Performance.
  • RuleResultTree.Inputs contains your inputs and the global and local parameters that were in scope, which makes failures easy to debug.
  • A parameter name must not equal the name of an input, and names must be unique within the workflow (globals) or the rule (locals). Duplicates are rejected when you add the workflow.

Next steps