Use custom types and custom actions
Call your own code from an expression
Expressions can call methods only on registered types. Create a static class, register it and use it in a rule.
public static class MyHelpers
{
public static bool CheckContains(string value, string commaSeparatedList)
{
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(commaSeparatedList))
{
return false;
}
return commaSeparatedList.Split(',').Contains(value);
}
}
var settings = new ReSettings { CustomTypes = new[] { typeof(MyHelpers) } };
var engine = new RulesEngine.RulesEngine(workflows, settings);
{ "RuleName": "AllowedCountry", "Expression": "MyHelpers.CheckContains(input1.country, \"india,usa\")" }
Notes:
- The class needs to be
public. - Give methods a concrete return type. A method that returns
objectmakes member access on its result fail, and the error message says so. - The built-in helper
ExpressionUtils.CheckContainsworks the same way and is always available. - Register only what rules need. See the type security model.
Pass an instance instead of a static class
Instance methods are available on any input, because input types are registered automatically (AutoRegisterInputType):
await engine.ExecuteAllRulesAsync("wf",
new RuleParameter("input1", data),
new RuleParameter("utils", new MyUtils()));
{ "RuleName": "Check", "Expression": "utils.CheckExists(input1.Property1)" }
Write a custom action
An action runs after a rule has been evaluated. Derive from ActionBase, read values from the context and return a result:
public class AuditAction : ActionBase
{
private readonly IAuditLog _log;
public AuditAction(IAuditLog log) => _log = log;
public override async ValueTask<object> Run(ActionContext context, RuleParameter[] ruleParameters)
{
var category = context.GetContext<string>("category");
await _log.WriteAsync(category, context.GetParentRuleResult().Rule.RuleName);
return "audited";
}
}
Register a factory, because a new instance is created for every use:
var settings = new ReSettings
{
CustomActions = new Dictionary<string, Func<ActionBase>>
{
{ "Audit", () => new AuditAction(auditLog) }
}
};
Use it by name in a rule:
{
"RuleName": "HighValue",
"Expression": "input1.total > 10000",
"Actions": {
"OnSuccess": { "Name": "Audit", "Context": { "category": "high-value-order" } }
}
}
The value returned by Run is available as RuleResultTree.ActionResult.Output. An exception thrown by Run is stored in ActionResult.Exception; see Error handling for when it is rethrown.
ActionContext.GetContext<T>(name) converts the context value to T (a string, number, list or object) and throws ArgumentException if the name is missing or the value cannot be converted. Use TryGetContext<T> when the value is optional.
Control when actions run
By default actions run inside ExecuteAllRulesAsync. To evaluate first and decide later, turn that off and call the action yourself for one rule:
var engine = new RulesEngine.RulesEngine(workflows, new ReSettings { AutoExecuteActions = false });
var results = await engine.ExecuteAllRulesAsync("Orders", input); // rules only
var action = await engine.ExecuteActionWorkflowAsync("Orders", "HighValue", // one rule and its action
new[] { new RuleParameter("input1", input) });
Chain rules with EvaluateRule
EvaluateRule runs another rule and returns its output, for example to try a cheaper discount when a better one fails:
{
"RuleName": "Discount20",
"Expression": "input1.total >= 20000",
"Actions": {
"OnSuccess": { "Name": "OutputExpression", "Context": { "expression": "input1.total * 0.8" } },
"OnFailure": { "Name": "EvaluateRule", "Context": { "workflowName": "Orders", "ruleName": "Discount10" } }
}
}
Use inputFilter to forward only some inputs, and additionalInputs to add computed ones. Both are described in Actions.
Evaluate an expression without workflows
RuleExpressionParser is the engine's expression evaluator and can be used on its own:
var parser = new RuleExpressionParser(new ReSettings());
var result = parser.Evaluate<string>("a + b", new[]
{
new RuleParameter("a", "Hello "),
new RuleParameter("b", "World")
});
// "Hello World"