Skip to content

Inheriting Constraint

Arif Yayalar (@ayayalar) edited this page Dec 30, 2019 · 2 revisions

Nested rules can inherit the constraint from the rule containing them (see example below). However, if the constraint is not relevant to a nested rule, you can override it.

Must be set in the Initialize, or the InitializeAsync method.
Example
class UpdateShipping : Rule<Order>
{
    public override void Initialize()
    {
        // Set constraint
        Configuration.Constraint = c => c.Price > 50m;
        
        // All nested rules will inherit the constraint defined in this rule.
        Configuration.NestedRulesInheritConstraint = true;
        
        // UpdatePromoCode inherits the constraint 
        AddRules(new UpdatePromoCode());
    }
    
    public override IRuleResult Invoke()
    {
        Model.FreeShipping = true;
        return null;
    }
}
// UpdatePromoCode inherits the constraint from UpdateShipping
class UpdatePromoCode : Rule<Order>
{
    public override void Initialize() =>  AddRules(new EmailConfirmation());

    public override IRuleResult Invoke()
    {
        Model.PromoCode = "156485";
        return null;
    }
}
// Overrides inherited constraint from UpdateShipping
class EmailConfirmation: Rule<Order>
{
    public override void Initialize()
    {
        Configuration.Constraint = c => true;
    }
    public override IRuleResult Invoke() => null;
}
Model
class Order
{
    public int Id { get; set; }
    public decimal Total { get; set; }
    public bool FreeShipping { get; set; }
}