Skip to content

Using snapshots

RagtimeWilly edited this page Mar 13, 2017 · 3 revisions

ISnapshotAggregate

If you wish to make use of the snapshotting functionality available in the event stores your aggregate must implement the ISnapshotAggregate interface. This is a simple extension of the IAggregate interface described here that provides methods for converting an aggregate to and from a snapshot.

An example

Extending the example customer aggregate described in the creating an aggregate page a version with snapshotting enabled would look like this:

public class Customer : AggregateBase, ISnapshotAggregate<CustomerSnapshot>
{
	public Customer()
	{
		RegisterHandler<CustomerCreated>(Apply);
		RegisterHandler<CustomerBalanceUpdated>(Apply);
	}

	private Customer(Guid id)
		: this()
	{
		RaiseEvent(new CustomerCreated(id));
	}

	public double Balance { get; private set; }

	public static Customer Create(Guid id)
	{
		return new Customer(id);
	}

	public void UpdateBalance(double newBalance)
	{
		if (newBalance < 0)
			throw InvalidOperationException("Balance must be greater or equal to 0");

		RaiseEvent(new CustomerBalanceUpdated(Id, newBalance));
	}

	private void Apply(CustomerCreated evt)
	{
		Id = evt.Id;
		Balance = 0;
	}

	private void Apply(CustomerBalanceUpdated evt)
	{
		Balance = evt.NewBalance;
	}

	public void RestoreFromSnapshot(CustomerSnapshot snapshot)
	{
		Id = snapshot.Id;
		Balance = snapshot.Balance;
	}

	public CustomerSnapshot ToSnapshot()
	{
		return new CustomerSnapshot()
		{
			Id = Id;
			Balance = Balance;
		};
	}
}

Then you just need to make sure a snapshot frequency is set when creating your event store (see here for more information) and snapshotting will be handled automatically by the event store.

Clone this wiki locally