Skip to content

Commit

Permalink
Merge pull request #54 from jacqueskang/feature/caching
Browse files Browse the repository at this point in the history
refactor: fix the issue that newly taken snapshot is lost after have …
  • Loading branch information
jacqueskang authored Feb 11, 2020
2 parents d0935b1 + 50949fa commit a07a5cf
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
11 changes: 9 additions & 2 deletions src/JKang.EventSourcing.Abstractions/Domain/Aggregate.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using JKang.EventSourcing.Events;
using JKang.EventSourcing.Snapshotting;
using System;
using System.Collections.Generic;
using System.Linq;
Expand Down Expand Up @@ -86,7 +85,7 @@ protected Aggregate(TKey id,

public IEnumerable<IAggregateEvent<TKey>> Events => _savedEvents.Concat(_unsavedEvents);

public IAggregateSnapshot<TKey> Snapshot { get; } = null;
public IAggregateSnapshot<TKey> Snapshot { get; private set; } = null;

public void TakeSnapshot()
{
Expand Down Expand Up @@ -194,6 +193,14 @@ public void Commit()
_aggregate._savedEvents.Enqueue(@evt);
}

if (Snapshot != null)
{
_aggregate.Snapshot = Snapshot;
while (_aggregate._savedEvents.Any() && _aggregate._savedEvents.First().AggregateVersion <= Snapshot.AggregateVersion)
{
_aggregate._savedEvents.Dequeue();
}
}
_aggregate._unsavedSnapshot = null;
_committed = true;
}
Expand Down
1 change: 1 addition & 0 deletions src/JKang.EventSourcing.Abstractions/Domain/IAggregate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public interface IAggregate<TKey>
{
TKey Id { get; }
int Version { get; }
IAggregateSnapshot<TKey> Snapshot { get; }
IEnumerable<IAggregateEvent<TKey>> Events { get; }
IAggregateChangeset<TKey> GetChangeset();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected AggregateRepository(
_snapshotStore = snapshotStore ?? throw new ArgumentNullException(nameof(snapshotStore));
}

protected async Task<IAggregateChangeset<TKey>> SaveAggregateAsync(TAggregate aggregate,
protected virtual async Task<IAggregateChangeset<TKey>> SaveAggregateAsync(TAggregate aggregate,
CancellationToken cancellationToken = default)
{
if (aggregate is null)
Expand All @@ -46,12 +46,12 @@ protected async Task<IAggregateChangeset<TKey>> SaveAggregateAsync(TAggregate ag
return changeset;
}

protected Task<TKey[]> GetAggregateIdsAsync()
protected virtual Task<TKey[]> GetAggregateIdsAsync()
{
return _eventStore.GetAggregateIdsAsync();
}

protected async Task<TAggregate> FindAggregateAsync(TKey id,
protected virtual async Task<TAggregate> FindAggregateAsync(TKey id,
bool ignoreSnapshot = false,
CancellationToken cancellationToken = default)
{
Expand Down

0 comments on commit a07a5cf

Please sign in to comment.