.NET Core event sourcing framework
A .NET Core event sourcing framework.
Easy to be integrated in ASP.NET Core web application, Lambda function or Azure function.
Support various of event store:
Let's implement a simple gift card management system with the following use cases:
I'm adopting DDD (Domain Driven Design) approach and implement the GiftCard entity as an Rich Domain Aggregate which encapsulates/protects its internal data/state, and contains itself business logics ensuring data integrity.
public sealed class GiftCardCreated : AggregateCreatedEvent
{
public GiftCardCreated(Guid aggregateId, DateTime timestamp, decimal initialCredit)
: base(aggregateId, timestamp)
{
InitialCredit = initialCredit;
}
public decimal InitialCredit { get; }
}public class GiftCardDebited : AggregateEvent
{
public GiftCardDebited(Guid aggregateId, int aggregateVersion, DateTime timestamp, decimal amount)
: base(aggregateId, aggregateVersion, timestamp)
{
Amount = amount;
}
public decimal Amount { get; }
}Notes:
AggregateEvent or AggregateCreatedEvent is not mandatory, but an aggreagte event must at least implement IAggregateEvent interface.…csharp public interface IGiftCardRepository { Task SaveGiftCardAsync(GiftCard giftCard); Task FindGiftCardAsync(Guid id); }
```csharp
public class GiftCardRepository : AggregateRepository,
IGiftCardRepository
{
public GiftCardRepository(IEventStore eventStore)
: base(eventStore)
{ }
public Task SaveGiftCardAsync(GiftCard giftCard) =>
SaveAggregateAsync(giftCard);
public Task FindGiftCardAsync(Guid id) =>
FindAggregateAsync(id);
}services
.AddScoped();
services
.AddEventSourcing(builder =>
{
builder.UseTextFileEventStore(x =>
x.Folder = "C:/Temp/GiftcardEvents");
});Notes:
// create a new gift card with initial credit 100
var giftCard = new GiftCard(100);
// persist the gift card
await _repository.SaveGiftCardAsync(giftCard);
// rehydrate the giftcard
giftCard = await _repository.FindGiftCardAsync(giftCard.Id);
// payments
giftCard.Debit(40); // ==> balance: 60
giftCard.Debit(50); // ==> balance: 10
giftCard.Debit(20); // ==> invalid operation exceptionSee this page.
See this page.
Consider install the nuget package JKang.EventSourcing.Persistence.Caching and inherit the CachedAggregateRepository class.
It leverages Microsoft.Extensions.Caching.Distributed.IDistributedCache to cache aggregate every time after loaded from or saved into repository.
Consider configuring a short sliding expiration (e.g., 5 sec) to reduce the chance of having cache out of date.
Contributions are welcome! Please see CONTRIBUTING.md for details on:
Please feel free to download, fork and/or provide any feedback!
No open issues yet, or sync has not completed.