7

For most of my applications I use a straight-forward DDD approach, which means separating the layers of the Onion Architecture, decoupling the domain from the infrastructure, etc. Two often-recurring building blocks, the repository and event bus, look like this (simplified).

public interface IRepository<TEntity, TKey>
    where TEntity : EntityBase<TKey>
{

    void Add(TEntity entity);

}

public interface IEventBus {

    void Publish<TEvent>(TEvent @event)
        where TEvent : IEvent;

}

Recently, I started looking into CQRS and I recognize a lot of similar patterns, again such as repositories, event & command buses. However, e.g. the repositories in CQRS are not responsible for storing/retrieving entities, but for managing aggregates and constructing event streams.

Now I'm wondering: do both of them work together? Or are they completely different approaches that just share a few common things?

jaco0646
  • 15,303
  • 7
  • 59
  • 83
xvdiff
  • 2,179
  • 2
  • 24
  • 47

1 Answers1

20

Yes, they are completely different approaches: CQRS does not mean event sourcing, but rather means separating writes from reads. You can do CQRS with and without event sourcing, these concepts are orthogonal to each other.

That being said, it is clear that with a CQRS-style architecture, your repositories are still responsible for storing and retrieving entities: Repositories are part of the domain language, and this language is not affected by architectural choices such as CQRS or non-CQRS. Here's a typical repository interface for CQRS applications, which is just the same as for non-CQRS applications; also, it remains the same if you are using event sourcing or not.

public interface IRepository<TEntity, TKey>
    where TEntity : EntityBase<TKey>
{

    void Add(TEntity entity);
    void Save(TEntity entity);
    TEntity retrieveByKey(TKey key);

}

Now, if you are not using event sourcing, your repository implementation, which is infrastructure, would, e.g., query a relational database and assemble the entity from the data found in the row for that particular key. If you are using event sourcing, your repository would be responsible for querying the event store, and project the event stream into the current state of the entity to return. All of this is part of the implementation and not of interest to the repository interface.

Alexander Langer
  • 2,883
  • 16
  • 18
  • Thank you very much for your comprehensive explaination. I wasn't aware that CQRS doesn't automatically means event sourcing. – xvdiff Aug 31 '14 at 21:39