Skip to content

Aggregate async methods

Andrey Leskov edited this page Jul 20, 2016 · 1 revision

###Overview Most aggregate methods are synchronious, as it implement domain logic. But sometimes long asynchronious calls are required, for example when aggregate need to call exteral service via http. In this case aggregate could execute other commands not been blocked until external call finished. As any other method, async method in aggregate should produce events. But result is Task with set of events, whitch will be available after Task complete. It is important for async method to be pure, e.g. not modifing any aggregate state in async manner. It will corrupt aggregate state. Async method invocations will not be persisted, and if aggregate instance will be crashed before async method call finish, all results will be lost. To persist invocations, use FutureEvents instead.

To use async calls aggreagate shoud be inherited from Aggregate class, and use RaiseEventsAsync method. Example:

        var aggregateId = Guid.NewGuid();
        var asyncCommand = new AsyncMethodCommand(43, Guid.NewGuid(),Guid.NewGuid(),TimeSpan.FromSeconds(3));
        var syncCommand = new ChangeAggregateCommand(42, aggregateId);

       var asyncCommandTask = GridNode.Execute<AggregateChangedEvent>(asyncCommand,
                                                ExpectedMessage.Once<AggregateChangedEvent>(nameof(AggregateChangedEvent.SourceId),
                                                asyncCommand.AggregateId));

        GridNode.Execute<AggregateChangedEvent>(syncCommand, Timeout,
                                                ExpectedMessage.Once<AggregateChangedEvent>(nameof(AggregateChangedEvent.SourceId),
                                                syncCommand.AggregateId)
                                                );

        var sampleAggregate = LoadAggregate<SampleAggregate>(syncCommand.AggregateId);
        Assert.AreEqual(syncCommand.Parameter.ToString(), sampleAggregate.Value);

        var asyncResult = asyncCommandTask.Result;
        Assert.AreEqual(asyncCommand.Parameter.ToString(), asyncResult.Value); 

You can find more detailed examples at https://github.com/andreyleskov/GridDomain/tree/master/GridDomain.Domain.Tests/AsyncAggregates

If async method will fall, exception will be passed back to caller keeping stack trace.

Clone this wiki locally