Skip to content

Data Sharing

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

Rules can share data with the other rules.

Example
class UpdateDescription : Rule<Product>
{
    public override IRuleResult Invoke()
    {
        // Store data to share with the other rules
        TryAdd("Description", "Desktop Computer");

        return null;
    }
}
class UpdateName : Rule<Product>
{
    public override IRuleResult Invoke()
    {
        // Retrieve data from another rule
        var description = TryGetValue("Description").To<string>();

        return null;
    }
}

TryGetValue blocks until the value is fetched. Throws TimeoutException after 15 seconds. (Timeout value is configurable).

Since synchronous rules invoked serially, you can only share data from the rules already been executed.

Async Example
class UpdateDescription : RuleAsync<Product>
{
    public override async Task<IRuleResult> InvokeAsync()
    {
        await TryAddAsync("Description", Task.FromResult<object>(Model.Total));
	return await RuleResult.Nil()
    }
}
class UpdateName : RuleAsync<Product>
{
    public override async Task<IRuleResult> InvokeAsync()
    {
	var description = (string) await TryGetValueAsync("Description");
	return await RuleResult.Nil()
    }
}