A Rules Engine in C# using Expression Trees
Introduction
In almost every business solution there will always be a module that will take a set of rules and perform a task/action if that rule is satisfied. It's called a rules engine. A rules engine could be a piece of module responsible for evaluating different rules defined and from there, the system may perform different tasks based from the rule(s) satisfied.
Airlines - ever wonder how fares are calculated? Or how seats are automatically assigned based from the user preference? There must be a rules
Hotel - discounts could be based from a rules engine to know which discount to use
Online shops (eBay, Amazon) - a rules engine must be used to determine how much rebate, discount, shipping cost etc should be used.
Rules engine is a very important aspect of a business solution. There can be many ways to create a rules engine. It could be a simple (but very long) switch case/if-else logic. Or Expression Trees.
In this blog, I will be discussing how Expression Trees can be used for creating a rules engine. But I would like to assume first that you understand Expression Trees.
The Logic
A Rule class containing 3 properties can be made. Left, Operator, Right. These represent the body of an expression. (5 > 4) 5 is Left, > is Operator, and 4 is Right.
From this class, you can now create a method that will take your Rule class and build the Expression tree from it. Then create a LamdbaExpression from that Expression you've build and compile and invoke it to see the result.
If there will be a parameter/variable in your Rule... eg. Name == "Aia", then you must create another class containing a property/field called Name and create a ParameterExpression using that class' type and use that to construct your expression. So your expression now knows that Name is a member of that class. Then you just need to create a LambdaExpression taking a parameter of that type (your class) to be able to evaluate the Expression built from the Rule.
The Code
I created a CodePlex project for this one. Although that project contains a more complex rules engine logic because I created it in such a way that a Rule may have its Right or its Left as another Rule. Making it a graph of rules.
Please if you're going to use it, take note of the copyright. Just make sure you include the copyrights and license.
Edit: I've changed the CodePlex project name to Yare because it seems weird that I have my full name as part of the product/project.
Edit: I've changed the CodePlex project name to Yare because it seems weird that I have my full name as part of the product/project.