Aggregate
can use View
this fact is described in Vaughn Vernon
's book:
Such Read Model Projections are frequently used to expose information to various clients (such as desktop and Web user interfaces), but they are also quite useful for sharing information between Bounded Contexts and their Aggregates. Consider the scenario where an Invoice Aggregate needs some Customer information (for example, name, billing address, and tax ID) in order to calculate and prepare a proper Invoice. We can capture this information in an easy-to-consume form via CustomerBillingProjection, which will create and maintain an exclusive instance of CustomerBilling-View. This Read Model is available to the Invoice Aggregate through the Domain Service named IProvideCustomerBillingInformation. Under the covers this Domain Service just queries the document store for the appropriate instance of the CustomerBillingView
Let's imagine our application should allow to create many users, but with unique names. Commands/Events flow:
CreateUser{Alice}
command sentUserAggregate
checksUsersListView
, since there are no users with name Alice, aggregate decides to create user and publish event.UserCreated{Alice}
event published // By UserAggregateUsersListProjection
processedUserCreated{Alice}
// for simplicity let's think UsersListProjection just accumulates users names if receivesUserCreated event
.CreateUser{Bob}
command sentUserAggregate
checksUsersListView
, since there are no users with name Bob, aggregate decides to create user and publish event.UserCreated{Bob}
event published // By UserAggregateCreateUser{Bob}
command sentUserAggregate
checksUsersListView
, since there are no users with name Bob, aggregate decides to create user and publish event.UsersListProjection
processedUserCreated{Bob}
.UsersListProjection
processedUserCreated{Bob}
.
The problem is - UsersListProjection
did not have time to process event and contains irrelevant data, aggregate used this irrelevant data. As result - 2 users with the same name created.
how to avoid such situations? how to make aggregates and projections consistent?