How inputs are typed
Rule expressions are compiled against .NET types, so every input needs a concrete type. RulesEngine accepts the following kinds of input and turns them into typed parameters.
flowchart TD
input["Input value"] --> kind{"What is it?"}
kind -- "ExpandoObject" --> expando["Create a class with one property per key<br/>(nested objects and lists recursively)<br/>and copy the values"]
kind -- "IDictionary of string and object" --> dict["Same as ExpandoObject:<br/>keys become properties"]
kind -- "Anything else<br/>POCO, anonymous type, JObject,<br/>JsonElement, primitive" --> asis["Used as is"]
kind -- "null" --> nul["Typed as object, or as T<br/>with RuleParameter.Create of T"]
expando --> typed["Typed object"]
dict --> typed
asis --> typed
nul --> typed
typed --> param["RuleParameter<br/>Name, Value, Type"]
param --> key["Type full name is part of the<br/>compiled rules cache key"]
Figure 1. From an input value to a RuleParameter.
Dynamic inputs (ExpandoObject and dictionaries)
- Each key becomes a property whose type comes from the value at runtime (a
stringvalue gives astringproperty, anintvalue anintproperty). - Nested objects become nested generated classes. Lists of objects become
List<T>of a generated class whose properties are the union of all elements, so a property that only appears in a later element is still available. - A
JsonElementscalar (what System.Text.Json produces) is unwrapped to a string, bool, int, long or double, soinput1.country == "india"works. Objects and arrays inside aJsonElementstayJsonElement. - Generated types are reused for objects with the same property names and types, so repeated calls with the same shape share compiled rules.
Consequences to be aware of
- A property whose value is
nullis typedobject. Comparisons that need a concrete type then fail to parse. Prefer typed classes, or pass a non-null sample value, when a property can benull. - The same property holding an
intin one call and alongin the next produces a different type, and therefore a recompile. - A dictionary input stops being a dictionary: use
input1.Keyrather thaninput1["Key"].
Typed inputs
POCOs, anonymous types, JObject and other objects are used as they are. For typed inputs, remember the type security model: methods on a type can be called from an expression only when the type is registered. AutoRegisterInputType (on by default) registers the input's own type, including generic arguments, array element types and nullable underlying types.
Naming inputs
// input1 and input2
await engine.ExecuteAllRulesAsync("Discount", customer, order);
// customer and order
await engine.ExecuteAllRulesAsync("Discount",
new RuleParameter("customer", customer),
new RuleParameter("order", order));
Names are matched case-insensitively unless ReSettings.IsExpressionCaseSensitive is true. Use RuleParameter.Create<T>(name, value) to keep the declared type when value may be null.