我正在寻找一个动态NRules的工作示例。实际上,我想把规则写在记事本文件中,并希望在运行时读取它们。
过去4天我一直在网上搜索,但没有找到任何东西。
任何帮助都是值得感激的。
NRules主要定位为一个规则引擎,其中规则是用c#编写的,并编译成程序集。还有一个配套项目https://github.com/NRules/NRules.Language,它定义了用于表示规则的文本DSL(称为Rule#)。它的功能不如c# DSL完整,但可能是您正在寻找的。
你仍然有一个c#项目,从文件系统或数据库加载文本规则,并驱动规则引擎。您将使用https://www.nuget.org/packages/NRules.RuleSharp包将文本规则解析为规则模型,并使用https://www.nuget.org/packages/NRules.Runtime将规则模型编译为可执行形式并运行规则。
给定一个域模型:
namespace Domain
{
public class Customer
{
public string Name { get; set; }
public string Email { get; set; }
}
}
给定一个文本文件,其规则称为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);
下面是规则驱动程序代码的示例:
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();
输出:Customer email is empty. Customer=John Do