我正在寻找动态 NRules 的工作示例。实际上,我想在记事本文件中编写规则并希望在运行时读取它们。
过去 4 天我一直在互联网上搜索它,但没有找到任何东西。
任何帮助都是可观的。
我正在寻找动态 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