-
Notifications
You must be signed in to change notification settings - Fork 15
/
EventSourcedAggregateRoot.cs
62 lines (48 loc) · 2.15 KB
/
EventSourcedAggregateRoot.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (c) TotalSoft.
// This source code is licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using NBB.Core.Abstractions;
using NBB.Domain.Abstractions;
namespace NBB.Domain
{
public abstract class EventSourcedAggregateRoot<TIdentity> : EmitApplyAggregateRoot<TIdentity>, IEventSourcedAggregateRoot<TIdentity>
{
public void LoadFromHistory(IEnumerable<object> history)
{
foreach (var domainEvent in history)
{
ApplyChanges(domainEvent, false);
}
}
}
public abstract class EventSourcedAggregateRoot<TIdentity, TMemento> : EventSourcedAggregateRoot<TIdentity>, ISnapshotableEntity, IMementoProvider<TMemento>
{
public int SnapshotVersion { get; private set; }
public virtual int? SnapshotVersionFrequency => null;
void ISnapshotableEntity.ApplySnapshot(object snapshot, int snapshotVersion)
{
var mementoProvider = this as IMementoProvider;
if (Version > 0)
throw new ApplicationException("Cannot apply snapshot on an already loaded aggregate");
Version = snapshotVersion;
SnapshotVersion = snapshotVersion;
mementoProvider.SetMemento(snapshot);
}
(object snapshot, int snapshotVersion) ISnapshotableEntity.TakeSnapshot()
{
var mementoProvider = this as IMementoProvider;
var snapshot = mementoProvider.CreateMemento();
var snapshotVersion = Version + GetUncommittedChanges().Count();
SnapshotVersion = snapshotVersion;
return (snapshot, snapshotVersion);
}
void IMementoProvider.SetMemento(object memento) => SetMemento((TMemento)memento) ;
object IMementoProvider.CreateMemento() => CreateMemento();
TMemento IMementoProvider<TMemento>.CreateMemento() => CreateMemento();
void IMementoProvider<TMemento>.SetMemento(TMemento memento) => SetMemento(memento);
protected abstract void SetMemento(TMemento memento);
protected abstract TMemento CreateMemento();
}
}