-
Notifications
You must be signed in to change notification settings - Fork 49
/
MartenRepository.cs
67 lines (57 loc) · 2.33 KB
/
MartenRepository.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
63
64
65
66
67
namespace EcommerceDDD.Core.Infrastructure.Marten;
public class MartenRepository<TA> : IEventStoreRepository<TA>
where TA : class, IAggregateRoot<StronglyTypedId<Guid>>
{
private readonly IDocumentSession _documentSession;
private readonly ILogger<MartenRepository<TA>> _logger;
public MartenRepository(
IDocumentSession documentSession,
ILogger<MartenRepository<TA>> logger)
{
_documentSession = documentSession;
_logger = logger;
}
/// <summary>
/// Stores uncommited events from an aggregate
/// </summary>
/// <param name="aggregate"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<long> AppendEventsAsync(TA aggregate, CancellationToken cancellationToken = default)
{
var events = aggregate.GetUncommittedEvents().ToArray();
var nextVersion = aggregate.Version + events.Length;
aggregate.ClearUncommittedEvents();
_documentSession.Events.Append(aggregate.Id.Value, nextVersion, events);
await _documentSession.SaveChangesAsync();
return nextVersion;
}
/// <summary>
/// Fetch domain events from the stream
/// </summary>
/// <param name="id"></param>
/// <param name="version"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<TA> FetchStreamAsync(Guid id, int? version = null, CancellationToken cancellationToken = default)
{
var aggregate = await _documentSession.Events.AggregateStreamAsync<TA>(id, version ?? 0);
return aggregate ?? throw new InvalidOperationException($"No aggregate found with id {id}.");
}
/// <summary>
/// Store integration events into the store
/// Outbox pattern
/// </summary>
/// <param name="event"></param>
/// <exception cref="ArgumentNullException"></exception>
public void AppendToOutbox(INotification @event)
{
if (@event is null)
throw new ArgumentNullException(nameof(@event));
var integrationEvent = IntegrationEvent
.FromNotification(@event!);
_logger.LogInformation($"Adding integration event {@event} to outbox...", @event);
_documentSession.Store(integrationEvent!);
}
}