我正在寻找一个动态NRules的工作示例。实际上,我希望在记事本文件中编写规则,并希望在运行时读取它们。
我已经在网上找了4天了,但什么也没找到。
任何帮助都是值得欣赏的。
发布于 2021-01-16 08:06:19
NRules主要定位为在C#中编写规则并将其编译为程序集的规则引擎。还有一个配套的项目https://github.com/NRules/NRules.Language,它定义了一个用于表达规则的文本领域特定语言(称为Rule#)。它的功能不如C# DSL完整,但可能就是你想要的。
在C#中,您仍然有一个项目可以从文件系统或DB加载文本规则,并驱动规则引擎。您将使用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 Dohttps://stackoverflow.com/questions/65724803
复制相似问题