Four ways to write a rule, one way to run it
Pick the style that fits the job. Every rule has the same code, message and severity, and works with every combinator, checker and explain tree.
- Rule class
- Builder
- Subject-typed
- Text expression
Derive from BaseBusinessRule. A rule is broken when its condition is true. Learn more
public sealed class OrderMustHaveItemsRule : BaseBusinessRule
{
private readonly Order _order;
public OrderMustHaveItemsRule(Order order)
{
_order = order;
}
public override string Code => "ORDER.NO_ITEMS";
public override string Message => "An order must contain at least one item.";
public override bool IsBroken() => _order.Items.Count == 0;
}
Build a rule inline from a lambda, with every metadata field on the builder. Learn more
IBusinessRule minimumTotalRule = BusinessRuleBuilder.Create("ORDER.BELOW_MINIMUM")
.WithName("Minimum order total")
.WithMessage("Order total must be at least 10.00.")
.WithSeverity(RuleSeverity.Error)
.WithCategory("Checkout")
.WithTags("orders", "checkout")
.When(() => order.Total < 10.00m)
.Build();
minimumTotalRule.Check(); // throws BusinessRuleValidationException when broken
One stateless instance validates whichever order you pass. Ideal for DI singletons. Learn more
public sealed class OrderItemsRequiredRule : BaseBusinessRule<Order>
{
public override string Code => "ORDER.NO_ITEMS";
public override string Message => "Order must contain at least one item.";
public override bool IsBroken(Order order) => order.Items.Count == 0;
}
IBusinessRule<Order> rule = new OrderItemsRequiredRule();
bool isBroken = rule.IsBroken(order);
Keep conditions in configuration. Parameters resolve per tenant at evaluation time. Learn more
IBusinessRule orderLimit = BusinessRuleBuilder.Create("ORDER.TOO_LARGE")
.WithMessage("Order exceeds the customer's limit.")
.WithCategory("Orders")
.WithParameter("maxOrderAmount", 10_000m)
.WhenExpression("amount > @maxOrderAmount")
.Build();
Everything a rule needs in production
Start with one rule. Add composition, rollout, tenancy and telemetry when you need them, without rewriting what you have.
Shadow rollout behind feature flags
Ship a new rule in shadow mode: violations are reported, never blocking. Then enforce it for a percentage of callers, then for everyone.
Read the guide- 1OffSkipped, passes
- 2ShadowReports, never blocks
- 3Enforced 10%Enforced for 10% of callers
- 4EnforcedEnforced for everyone
Compose anything
And, Or and Not, plus All, Any, AtLeast and Exactly groups with short-circuit and parallel evaluation.
Read the guideExplain every verdict
One evaluation returns a tree of every node it visited, with outcome, reason and timing.
Read the guideBatch checking
Run many rules in one call. Filter by severity, category or tag, pick a fault policy, read the ledger.
Read the guideSpecifications to SQL
The same rule checks one object in memory and filters an IQueryable in the database.
Read the guideText expressions
Write amount > @maxOrderAmount as text and see the exact values it was evaluated with.
Read the guidePer-tenant parameters
Externalize limits per tenant without touching rule code. The most specific matching scope wins.
Read the guide| Scope | @maxOrderAmount |
|---|---|
| Global | 10,000 |
| tenant=acme | 50,000 |
| region=EU;tenant=acme | 70,000wins |
Conditional and cached
Run a rule only when a precondition holds. Cache slow verdicts for a time, per rule or per key.
Read the guideLogs, traces, metrics
Structured ILogger entries, OpenTelemetry spans and Meter instruments for every evaluation.
Read the guideTest tools built in
Outcome coverage, a boundary finder, CsCheck property checks and smoke-test mutants.
Read the guideInstall the core. Add only what you use.
All six packages ship together with the same version number. Every companion package depends only on the core and the library it integrates with.
Masterly.BusinessRulesRules, builders, composition, batch checking, context, caching, feature gates, parameters and specifications.
Masterly.BusinessRules.ExpressionsRule conditions written as text, with explanations that show the bound values.
Masterly.BusinessRules.DiagnosticsStructured ILogger logging, OpenTelemetry spans and metrics for rule evaluation.
Masterly.BusinessRules.DependencyInjectionAssembly scanning, injectable rule runners and per-tenant rule sets.
Masterly.BusinessRules.FeatureManagementDrives feature-gated rules from Microsoft.FeatureManagement flags and variants.
Masterly.BusinessRules.TestingOutcome coverage, boundary finder, property checks and mutants for your test projects.
Write your first rule in five minutes.
The Quick Start defines two rules, checks one, then checks both together.