Load rules from files, strings, code or a database
The engine needs Workflow objects. It does not care where they come from. This page shows the common sources.
From a JSON file
using System.Text.Json;
using RulesEngine.Models;
var workflows = JsonSerializer.Deserialize<Workflow[]>(File.ReadAllText("workflows.json"));
var engine = new RulesEngine.RulesEngine(workflows);
The file is an array of workflows (see the workflow JSON reference). With System.Text.Json the property names are case-sensitive, so use the exact names from the reference.
From JSON strings
The constructor can take the JSON of each workflow directly. Every string holds one workflow object, not an array:
var engine = new RulesEngine.RulesEngine(new[] { workflowJson1, workflowJson2 });
From code
var workflow = new Workflow
{
WorkflowName = "Discount",
Rules = new[]
{
new Rule
{
RuleName = "Small",
SuccessEvent = "5",
Expression = "input1.total < 100"
}
}
};
var engine = new RulesEngine.RulesEngine();
engine.AddWorkflow(workflow);
From a database with Entity Framework
Workflow and Rule are plain classes, so they can be mapped by EF Core. The demo project contains a complete SQLite example: RulesEngineContext maps the model, and EFDemo loads it:
var workflows = db.Workflows.Include(w => w.Rules).ThenInclude(r => r.Rules).ToArray();
var engine = new RulesEngine.RulesEngine(workflows);
Add one ThenInclude for every additional level of nested rules you use.
From blob storage, Cosmos DB or any other store
Read the content with that store's SDK, deserialize it into Workflow objects as shown above and pass them to the engine. Keep that code in your own wrapper so the rest of your application only sees the engine.
Add, replace and remove workflows at runtime
| Goal | Call |
|---|---|
| Add a new workflow | AddWorkflow(workflow). Throws RuleValidationException if the name already exists. |
| Add or replace | AddOrUpdateWorkflow(workflow). The next execution recompiles that workflow. |
| Remove | RemoveWorkflow("Name") |
| Remove everything | ClearWorkflows() |
| Check or list | ContainsWorkflow("Name"), GetAllRegisteredWorkflowNames() |
Workflows are validated when you add them; an invalid workflow throws RuleValidationException and is not stored. See Caching and invalidation for what a replace does to compiled rules.
Reuse rules across workflows
A workflow can include the rules of other registered workflows with WorkflowsToInject:
{ "WorkflowName": "Checkout", "WorkflowsToInject": ["CommonRules"], "Rules": [ ... ] }
Only the rules are injected, not the other workflow's GlobalParams. Circular injection throws InvalidOperationException when the workflow is first executed.