Skip to content

Instantly share code, notes, and snippets.

@JefClaes
Created October 2, 2013 14:16
Show Gist options
  • Select an option

  • Save JefClaes/6794475 to your computer and use it in GitHub Desktop.

Select an option

Save JefClaes/6794475 to your computer and use it in GitHub Desktop.
ES Demo snippet
using System;
using System.Collections.Generic;
namespace EventSourcing
{
public class Program
{
public static void Main(string[] args)
{
var acc = new Account();
acc.Withdraw(10);
acc.Withdraw(20);
acc.Withdraw(30);
acc.Withdraw(40);
acc.Deposit(50);
foreach (var @event in acc.RecordedEvents())
Console.WriteLine(@event);
var acc2 = new Account();
acc2.Initialize(acc.RecordedEvents());
acc2.Deposit(10);
acc2.Deposit(20);
acc2.Deposit(30);
acc2.Deposit(40);
acc2.Deposit(50);
acc2.Withdraw(500000);
foreach (var @event in acc2.RecordedEvents())
Console.WriteLine(@event);
Console.ReadLine();
}
public class Account
{
private int _amount = 0;
private readonly EventRecorder _eventRecorder;
public Account()
{
_eventRecorder = new EventRecorder();
}
public void Initialize(IEnumerable<IEvent> events)
{
foreach (var @event in events)
When((dynamic)@event);
}
public IEnumerable<IEvent> RecordedEvents()
{
return _eventRecorder.RecordedEvents();
}
public void Deposit(int amount)
{
Apply(new AmountDeposited(amount));
}
public void Withdraw(int amount)
{
if (amount > AmountPolicy.Maximum)
{
_eventRecorder.Record(new WithdrawalAmountExceeded(amount));
return;
}
Apply(new AmountWithdrawn(amount));
}
private void Apply(IEvent @event)
{
When((dynamic)@event);
_eventRecorder.Record(@event);
}
private void When(AmountWithdrawn @event)
{
_amount -= @event.Amount;
}
private void When(AmountDeposited @event)
{
_amount += @event.Amount;
}
}
public interface IEvent { }
public class EventRecorder
{
private readonly List<IEvent> _events = new List<IEvent>();
public void Record(IEvent @event)
{
_events.Add(@event);
}
public IEnumerable<IEvent> RecordedEvents()
{
return _events;
}
}
public class AmountWithdrawn : IEvent
{
public AmountWithdrawn(int amount)
{
Amount = amount;
}
public int Amount { get; private set; }
public override string ToString()
{
return string.Format("Amount withdrawn: {0}", Amount);
}
}
public class AmountDeposited : IEvent
{
public AmountDeposited(int amount)
{
Amount = amount;
}
public int Amount { get; private set; }
public override string ToString()
{
return string.Format("Amount deposited: {0}", Amount);
}
}
public class WithdrawalAmountExceeded : IEvent
{
public WithdrawalAmountExceeded(int amount)
{
Amount = amount;
}
public int Amount { get; private set; }
public override string ToString()
{
return string.Format("Amount exceeded: {0}", Amount);
}
}
public class AmountPolicy
{
public static int Maximum { get { return 5000; } }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment