I'm looking for a working example of dynamic NRules. Actually, I want to write the rules in a notepad file and want to read them at runtime.
I have been searching it through the internet for last 4 days but didn't find anything.
Any help is appreciable.
NRules is primarily positioned as a rules engine where rules are authored in C#, and compiled into assemblies. There is a companion project https://github.com/NRules/NRules.Language that defines a textual DSL (called Rule#) for expressing rules. It's less feature-complete than C# DSL, but is potentially what you are looking for.
You would still have a project in C# that loads the textual rules from the file system or a DB, and drives the rules engine. You would use https://www.nuget.org/packages/NRules.RuleSharp package for parsing the textual rules into a rule model, and https://www.nuget.org/packages/NRules.Runtime to compile the rule model into an executable form and run the rules.
Given a domain model:
namespace Domain
{
public class Customer
{
public string Name { get; set; }
public string Email { get; set; }
}
}
And given a text file with rules called MyRuleFile.txt
:
using Domain;
rule "Empty Customer Email"
when
var customer = Customer(x => string.IsNullOrEmpty(x.Email));
then
Console.WriteLine("Customer email is empty. Customer={0}", customer.Name);
Here is an example of how the rules driver code might look like:
var repository = new RuleRepository();
repository.AddNamespace("System");
//Add references to any assembly that the rules are using, e.g. the assembly with the domain model
repository.AddReference(typeof(Console).Assembly);
repository.AddReference(typeof(Customer).Assembly);
//Load rule files
repository.Load(@"MyRuleFile.txt");
//Compile rules
var factory = repository.Compile();
//Create a rules session
var session = factory.CreateSession();
//Insert facts into the session
session.Insert(customer);
//Fire rules
session.Fire();
Output:
Customer email is empty. Customer=John Do