Skip to content

Instantly share code, notes, and snippets.

@MarkNijhof
Created August 1, 2010 20:56
Show Gist options
  • Save MarkNijhof/503758 to your computer and use it in GitHub Desktop.
Save MarkNijhof/503758 to your computer and use it in GitHub Desktop.
namespace Fohjin.DDD.EventStore.Storage.Memento
{
public interface IOrginator
{
IMemento CreateMemento();
void SetMemento(IMemento memento);
}
}
void IEventProvider.Clear()
{
_entityEventProviders.ForEach(x => x.Clear());
_appliedEvents.Clear();
}
namespace Fohjin.DDD.EventStore
{
public interface IEventProvider
{
void Clear();
void LoadFromHistory(IEnumerable<IDomainEvent> domainEvents);
void UpdateVersion(int version);
Guid Id { get; }
int Version { get; }
IEnumerable<IDomainEvent> GetChanges();
}
}
private void registerEvents()
{
RegisterEvent<ClientCreatedEvent>(onNewClientCreated);
RegisterEvent<ClientMovedEvent>(onNewClientMoved);
}
private void onNewClientCreated(ClientCreatedEvent clientCreatedEvent)
{
Id = clientCreatedEvent.ClientId;
_clientName = new ClientName(clientCreatedEvent.ClientName);
_address = new Address(clientCreatedEvent.Street, clientCreatedEvent.StreetNumber, clientCreatedEvent.PostalCode, clientCreatedEvent.City);
_phoneNumber = new PhoneNumber(clientCreatedEvent.PhoneNumber);
}
private void onNewClientMoved(ClientMovedEvent clientMovedEvent)
{
_address = new Address(clientMovedEvent.Street, clientMovedEvent.StreetNumber, clientMovedEvent.PostalCode, clientMovedEvent.City);
}
private readonly Dictionary<Type, Action<IDomainEvent>> _registeredEvents;
protected void RegisterEvent<TEvent>(Action<TEvent> eventHandler) where TEvent : class, IDomainEvent
{
_registeredEvents.Add(typeof(TEvent), theEvent => eventHandler(theEvent as TEvent));
}
public void Delegate(IDomainEvent domainEvent)
{
onNewClientCreated(domainEvent as ClientCreatedEvent);
}
private void apply(Type eventType, IDomainEvent domainEvent)
{
Action<IDomainEvent> handler;
if (!_registeredEvents.TryGetValue(eventType, out handler))
throw new UnregisteredDomainEventException(string.Format("The requested domain event '{0}' is not registered in '{1}'", eventType.FullName, GetType().FullName));
handler(domainEvent);
}
public void Withdrawl(Amount amount)
{
Guard();
IsBalanceHighEnough(amount);
var newBalance = _balance.Withdrawl(amount);
Apply(new CashWithdrawnEvent(newBalance, amount));
}
protected void Apply<TEvent>(TEvent domainEvent) where TEvent : class, IDomainEvent
{
domainEvent.AggregateId = Id;
domainEvent.Version = GetNewEventVersion();
apply(domainEvent.GetType(), domainEvent);
_appliedEvents.Add(domainEvent);
}
IEnumerable<IDomainEvent> IEventProvider.GetChanges()
{
return _appliedEvents
.Concat(GetEntityEvents())
.OrderBy(x => x.Version)
.ToList();
}
private IEnumerable<IDomainEvent> GetEntityEvents()
{
return _entityEventProviders
.SelectMany(entity => entity.GetChanges());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment