RulesEngine 概述
RulesEngine是Microsoft推出的一个规则引擎项目,用于系统中抽象出的业务逻辑/规则/策略。在我们开发的过程中,避免不了的是跟这种反反复复的业务逻辑进行处理,而对于这种动态的规则来说的话,它是比较优雅的一种方式,使用我们减少了对我们代码或者说项目的修改。
属性 描述
RuleName 规则名称
Properties 规则属性,获取或设置规则的自定义属性或者标记
Operator 操作符
ErrorMessage 错误消息
Enabled 获取和设置规则是否已启用
RuleExpressionType 规则表达式类型,默认为LambdaExpression,当然目前只有这么一个
WorkflowRulesToInJect 注入工作流程规则
Rules 规则
LocalParams 本地参数
Expression 表达树
Actions
SuccessEvent 完成事件,默认为规则名称
nugit引用RulesEngine
- using Newtonsoft.Json;
- using RulesEngine.Models;
- using System;
- using System.Collections.Generic;
-
- namespace Rules
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- // 定义规则
- var rulesStr = @"[{
- ""WorkflowName"": ""UserInputWorkflow"",
- ""Rules"": [
- {
- ""RuleName"": ""CheckAge"",
- ""ErrorMessage"": ""年龄必须大于18岁."",
- ""ErrorType"": ""Error"",
- ""RuleExpressionType"": ""LambdaExpression"",
- ""Expression"": ""Age > 18""
- },
- {
- ""RuleName"": ""CheckIDNoIsEmpty"",
- ""ErrorMessage"": ""身份证号不可以为空."",
- ""ErrorType"": ""Error"",
- ""RuleExpressionType"": ""LambdaExpression"",
- ""Expression"": ""IdNo != null""
- }
- ]
- }] ";
-
- var workflowRules = JsonConvert.DeserializeObject<List<WorkflowRules>>(rulesStr);
-
- var rulesEngine = new RulesEngine.RulesEngine(workflowRules.ToArray());
-
- var userInput = new UserInput
- {
- IdNo = null,
- Age = 18
- };
-
- List<RuleResultTree> resultList = rulesEngine.ExecuteAllRulesAsync("UserInputWorkflow", userInput).Result;
- foreach (var result in resultList)
- {
- Console.WriteLine("验证成功:{0},消息:{1}", result.IsSuccess, result.ExceptionMessage);
- }
-
- }
- }
-
- public class UserInput
- {
- public string IdNo { get; set; }
- public int Age { get; set; }
- }
- }