Event Sourcing and Read Model generation

前端 未结 3 1690
时光说笑
时光说笑 2021-01-30 14:08

Assuming Stack Overflow domain problem and the following definition of events:

UserRegistered(UserId, Name, Email)
UserNameChanged(UserId, Name)
QuestionAsked(Us         


        
3条回答
  •  梦毁少年i
    2021-01-30 14:26

    Pull events from the EventStore.

    Remember - Your read models need to have read-only access to the EventStore already. Read Models are disposable. They are simply cached views. You should be able to delete / expire your Read Models at any time - and automatically rebuild your ReadModels from the EventStore. So - your ReadModelBuilders must already be able to query for past events.

    public class QuestionEventsHandler
    {
        public void Handle(QuestionAsked question)
        {
            // Get Name of User
            var nameChangedEvent = eventRepository.GetLastEventByAggregateId(question.UserId);
    
            var item = new QuestionItem(
                question.UserId, 
                question.QuestionId, 
                question.Title, 
                question.Question, 
    
                nameChangedEvent.Name
        }
    }
    

    Also realize - the EventStore repository need not be the true EventStore, although it certainly could be. The advantage of distributed systems is that you can easily replicate the EventStore, if you needed, closer to your ReadModels.

    I encountered this exact same scenario... where I needed more data than was available in a single event. This is especially true for Create-type events which require populating a new ReadModel with initial state.

    From Read Models: You could pull from other Read Models. But I really don't recommend this, as you would introduce a big ball of dependency mud where views depend on views depend on views.

    Additional Data in Events: You really don't want to bloat your events with all the extra data you'll need for views. It will really hurt you when your domain changes & you need to migrate events. Domain Events have specific purposes - they represent state changes. Not view data.

    Hope this helps -

    Ryan

提交回复
热议问题