milandjukic88
milandjukic88

Reputation: 1115

Event Sourcing and Clean Architecture - does domain model need to handle events?

I'm still learning clean architecture and now I'm trying to implement event sourcing in project. I have 2 projects, one that hold commands and events and one where is domain model. By definition of clean architecture domain model is center of everything. Everytthing references him. But, all examples that I found shows that domain model have Apply methods for each event.

Do I need to do this in domain model? Or is some other way?

In some point in code I need to reconstruct domain model from events something like this:

public void Load(events){
foreach(var event in events)
{
   Apply(event);
}}

This should be in domain model class, like Apply method. Apply method changes internal state of domain model.

Upvotes: 1

Views: 1431

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57214

all examples that I found shows that domain model have Apply methods for each event. Do I need to do this in domain model?

You don't "have to" do that, but it is a likely outcome in a Kingdom of Nouns design. Since much of the early development of domain driven design (Java) and event sourcing (C#) were taking place in the Kingdom of Nouns, the examples tend to share these patterns.

With the Apply pattern, you are seeing the result of two different ideas.

One, the idea that all event sourced models have the same underlying data structure (Truth is the history of events), so we should be using a single common, general purpose implementation for all of them.

Two, that the information we cache within the data model (aka the model object's "properties") should look "the same" whether we are looking at the original object that processed the command or if we are instead looking at a copy of that model loaded from the history.

Thus, a pattern emerged that models tend to "inherit" from some base class that owns an event history and an api for coordinating changes to both the history and the models own internal cache, and that command handlers on the model work by first calculating what changes (events) should happen, then applying those changes using the same code paths that would be used when reloading the event history.

Upvotes: 2

Related Questions