Projections
A projection is a representation of an object using a different perspective. In the context of CQRS, projections are queryable models on the "read" side that never manipulate the original data (events in event-sourced systems) in any way. Projections should be designed in a way that is useful and convenient for the reader (API, UI, etc.).
Cronus supports non-event-sourced and event-sourced projections with snapshots.
Defining a projection
To create a projection, create a class for it that inherits ProjectionDefinition<TState, TId>
. The id can be any type that implements the IBlobId
interface. All ids provided by Cronus implement this interface but it is common to create your own for specific business cases. The ProjectionDefinition<TState, TId>
base class provides a Subscribe()
the method that is used to create a projection id from an event. This will define an event-sourced projection with a state that will be used to persist snapshots.
Use the IEventHandler<TEvent>
interface to indicate that the projection can handle events of the specified event type. Implement this interface for each event type your projection needs to handle.
Create a class for the projection state. The state of the projection gets serialized and deserialized when persisting or restoring a snapshot. That's why it must have a parameterless constructor, a data contract and data members.
You can define a non-event-sourced projection by decorating it with the IProjection
interface. This is useful when you want to persist the state in an external system (e.g. ElasticSearch, relational database).
By default, all projections' states are being persisted as snapshots. If you want to disable this feature for a specific projection, use the IAmNotSnapshotable
interface.
Querying a projection
To query a projection, you need to inject an instance of IProjectionReader
in your code and invoke the Get()
or GetAsync()
method. The returned object will be of type ReadResult
or Task<ReadResult>
containing the projection and a few properties indicating if the loading was successful.
Projection versioning
TODO
Best Practices
You can/should/must...
a projection must be idempotent
a projection must not issue new commands or events
You should not...
a projection should not query other projections. All the data of a projection must be collected from the Events' data
Last updated
Was this helpful?