Skip to content

Before and After Invoke

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

BeforeInvoke or AfterInvoke gets invoked before and after the Invoke method.

It is not called if the rule marked as Skip or the Constraint (if there are any set on the rule) check failed.

Example
class IsValidTotal : Rule<Order>
{   
    private Stopwatch _stopwatch;

    public override IRuleResult Invoke()
    {
        if (Model.Total <= 0.0m) throw new InvalidOperationException();            
        
        return null;
    }

    public override void BeforeInvoke() => _stopwatch = Stopwatch.StartNew();
    	
    public override void AfterInvoke() => total = _stopwatch.ElapsedMilliseconds;    
}
Async Example
class IsValidTotalAsync : RuleAsync<Order>
{   
    private Stopwatch _stopwatch;

    public override Task<IRuleResult> InvokeAsync()
    {
        if (Model.Total <= 0.0m) throw new InvalidOperationException();            
        
        return RuleResult.Nil();
    }

    public async override Task BeforeInvokeAsync() 
    {
        _stopwatch = Stopwatch.StartNew();
        
        await base.BeforeInvokeAsync();
    }
    	
    public async override Task AfterInvokeAsync()
    {
        var totalRuntimeMs = _stopwatch.ElapsedMilliseconds;
        
        await base.AfterInvokeAsync();
    }
}
Model
class Order
{
    public int Id { get; set; }
    public decimal Total { get; set; }
    public bool FreeShipping { get; set; }
}