Now we have implemented the persistence of our domain and read models, we can start to revisit the implementation so that we can switch over to an event-sourced domain model instead.

We need a way to store and retrieve new events so I have added a private property and exposed a read-only collection as well as a clear method that our repository can access when it deals with persisting the events.

The next thing i want to do is before I call the apply method for making updates to my domain object, I want to add this to my list of uncommitted events.

Because I will always want to add my event to a list before applying it, i can refactor those two steps into a single RaiseEvent(DomainEvent) method so that I can ensure those two happen for all new events.

I’ve also added a new ApplyMethod that takes in the DomainEvent casting it to a dynamic type so it can resolve the correct method that handles the specific domain event and apply the changes.

Now I still have my read views that i want to continue persisting as is and not use event source, so I’ll create a new interface to distinguish aggregate roots from the read models.

I created a new entity to persist event data and a new implementation of the repository for Aggregate roots.

Instead of simply saving the state, we serialize the list of new events and store them along with the event type and aggregate identifier.

When we want to retrieve a specific aggregate or individual later on, we can simply fetch all the events with that aggregate id, and apply them to a new object in order to ‘rehydrate’ the object.

The latest changes can be found Here

Leave a comment