Skip to content

Projection

Duncan Jones edited this page Oct 4, 2020 · 4 revisions

Projection

A projection is a piece of code that runs over the event stream for an entity in order to derive some state information about that entity.

For each event in the stream it needs to decide (a) am I interested in this kind of event and if so (b) what do I do with it.

Example

The following projection runs over an event stream for a bank account. It processes (through the IHandleEventType interface) any Withdrawalevents or Depositevents and from this calculates the current balance of the account.

    /// <summary>
    /// The running balance of the account
    /// </summary>
    public class Balance
        : ProjectionBase,
        IHandleEventType<MoneyDeposited>,
        IHandleEventType<MoneyWithdrawn >
    {

        private decimal currentBalance;

        /// <summary>
        /// The current balance after the projection has run over a bank account event stream
        /// </summary>
        public decimal CurrentBalance
        {
            get
            {
                return currentBalance;
            }
        }

        public void HandleEventInstance(MoneyDeposited eventInstance)
        {
            if (null != eventInstance )
            {
                currentBalance += eventInstance.AmountDeposited;
            }
        }

        public void HandleEventInstance(MoneyWithdrawn eventInstance)
        {
            if (null != eventInstance )
            {
                currentBalance -= eventInstance.AmountWithdrawn;
            }
        }
    }

The projection (and which event stream) to use is determined by the projection attribute which is used to bind a parameter to that projection. Projections are run on demand so that the cost of getting the state is borne by whatever function is going to make use of that state.

When a projection completes it returns the state values it has derived and also an AsOfSequenceNumber that is the number of the highest event in the stream used to derive that state. This means it is possible to save that projection state and pick up from that sequence number in a future projection run.

Clone this wiki locally