Skip to content

Instantly share code, notes, and snippets.

@marcofranssen
Created August 4, 2011 09:01
Show Gist options
  • Save marcofranssen/1124767 to your computer and use it in GitHub Desktop.
Save marcofranssen/1124767 to your computer and use it in GitHub Desktop.
Event tracking for your aggregates to prepare your eventstore
public abstract class BisAggregateRoot : AggregateRootMappedByConvention
{
private readonly List<object> _appliedEvents = new List<object>();
protected readonly ICredentials Credentials = NcqrsEnvironment.Get<ICredentials>();
protected BisAggregateRoot()
{
}
protected BisAggregateRoot(Guid id) : base(id)
{
}
//Tracking of changes can be removed here when the eventtracker can track the construction of the AR.
public IEnumerable<object> GetChanges()
{
return _appliedEvents.ToArray();
}
protected override void OnEventApplied(Ncqrs.Eventing.UncommittedEvent appliedEvent)
{
_appliedEvents.Add(appliedEvent.Payload);
base.OnEventApplied(appliedEvent);
}
}
public static class BuilderExtensions
{
public static TAggregateRoot TrackChanges<TAggregateRoot>(this TAggregateRoot target) where TAggregateRoot : BisAggregateRoot
{
EventTracker.RegisterAggregate(target);
return target;
}
public static IEnumerable<object> GetChanges(this BisAggregateRoot target)
{
return EventTracker.GetChanges(target);
}
public static ScientificStudy WithDefaultVisitDefined(this ScientificStudy target)
{
target.DefineVisit(Default.Id.For.Visit, "",Default.Subgroup.Men, "");
return target;
}
//Other members left for convenience
}
public static class EventTracker
{
private static readonly Dictionary<Guid, List<object>> Trackers = new Dictionary<Guid, List<object>>();
public static void RegisterAggregate<TAggregateRoot>(TAggregateRoot aggregateRoot) where TAggregateRoot : BisAggregateRoot
{
var aggregateId = aggregateRoot.EventSourceId;
if (Trackers.ContainsKey(aggregateId)) return;
aggregateRoot.EventApplied += aggregateRoot_EventApplied;
Trackers.Add(aggregateId, new List<object>());
}
public static IEnumerable<object> GetChanges<TAggregateRoot>(TAggregateRoot aggregateRoot) where TAggregateRoot : BisAggregateRoot
{
var aggregateId = aggregateRoot.EventSourceId;
List<object> changes;
if(Trackers.TryGetValue(aggregateId, out changes))
return changes.AsReadOnly();
return new List<object>();
}
private static void aggregateRoot_EventApplied(object sender, EventAppliedEventArgs e)
{
var aggregateId = ((BisAggregateRoot)sender).EventSourceId;
List<object> changes;
if (Trackers.TryGetValue(aggregateId, out changes))
{
var payload = e.Event.Payload;
changes.Add(payload);
}
}
}
You can use the eventtracker like this.
New.ScientificStudy.TrackChanges().WithDefaultVisitDefined().WithDefaultSopAdded().WithDefaultSpecimenAdded().GetChanges();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment