0001. Compile rule expressions to cached delegates with System.Linq.Dynamic.Core
Status
Accepted. Recorded retroactively.
Context and problem statement
Rules are stored as text outside the application (JSON, a database) and change without redeploying. They must be evaluated many times, with inputs whose types are known only at run time, often as objects deserialized from JSON. The engine needs an expression language that authors can read, and fast evaluation.
Decision drivers
- Rules are authored by people who know C# or LINQ-like syntax.
- Evaluation happens on hot paths, so per-call parsing is not acceptable.
- Inputs can be typed objects, anonymous types or dynamic objects.
- Avoid inventing and maintaining a new language.
Considered options
- Parse the text with System.Linq.Dynamic.Core into an expression tree, compile it to a delegate once and reuse it.
- Interpret an expression tree or script on every evaluation.
- Compile rules with the Roslyn scripting APIs.
- Define a custom rule DSL.
Decision outcome
Parse with System.Linq.Dynamic.Core, build an Expression<Func<object[], bool>> for each rule, compile it (with Expression.Compile(), or FastExpressionCompiler when UseFastExpressionCompiler is on) and cache the delegate. See Evaluation pipeline.
Consequences
- Good: after the first call a rule is a compiled delegate, so evaluation is fast.
- Good: the expression language is the documented, widely used System.Linq.Dynamic.Core language, with LINQ support.
- Good: the parser can be reused on its own (
RuleExpressionParser). - Bad: compilation costs time, so there is a warm-up on the first use of each input shape. See Performance.
- Bad: the engine depends on the behavior and security posture of System.Linq.Dynamic.Core (see ADR 0002).
- Bad: dynamic inputs have to be turned into typed objects before an expression can be compiled (see How inputs are typed).