Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 18 additions & 21 deletions docs/src/content/docs/persistence/serialisation.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,29 @@ Then, you can call this code in your bootstrap code:
BookingEvents.MapBookingEvents();
```

### Auto-registration of types
### Auto-registration with source generator

For convenience purposes, you can avoid manual mapping between type names and types by using the `EventType` attribute.
The recommended way to register event types is to use the `[EventType]` attribute combined with the Eventuous source generator. The generator automatically discovers all types decorated with `[EventType]` in your project and generates a module initializer that registers them at startup — no manual registration code needed.

Annotate your events with it like this:
Annotate your events with the `[EventType]` attribute:

```csharp
[EventType("V1.FullyPaid")]
public record BookingFullyPaid(string BookingId, DateTimeOffset FullyPaidAt);

[EventType("V1.RoomBooked")]
public record RoomBooked(string RoomId, LocalDate CheckIn, LocalDate CheckOut, float Price);
```

Then, use the registration code in the bootstrap code:
That's it. The source generator produces a module initializer class per assembly, which calls `TypeMap.Instance.AddType(...)` for each annotated event type. Registration happens automatically when the assembly is loaded — you don't need to write any startup code.

:::tip
Eventuous also includes a diagnostic analyzer (`EVTC001`) that warns you when an event type is used in aggregates or state projections but is missing the `[EventType]` attribute.
:::

### Reflection-based registration

As an alternative to the source generator, you can use reflection-based registration. This scans assemblies at runtime for types decorated with `[EventType]`:

```csharp
TypeMap.RegisterKnownEventTypes();
Expand All @@ -75,23 +86,9 @@ The registration won't work if event classes are defined in another assembly, wh
TypeMap.RegisterKnownEventTypes(typeof(BookingFullyPaid).Assembly);
```

If you use the .NET version that supports module initializers, you can register event types in the module. For example, if the domain event classes are located in a separate project, add the file `DomainModule.cs` to that project with the following code:

```csharp title="DomainModule.cs"
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Eventuous;

namespace Bookings.Domain;

static class DomainModule {
[ModuleInitializer]
[SuppressMessage("Usage", "CA2255", MessageId = "The \'ModuleInitializer\' attribute should not be used in libraries")]
internal static void InitializeDomainModule() => TypeMap.RegisterKnownEventTypes();
}
```

Then, you won't need to call the `TypeMap` registration in the application code at all.
:::note
With the source generator in place, calling `RegisterKnownEventTypes()` is typically unnecessary. The generator handles registration at compile time, which is both more reliable and avoids the overhead of runtime assembly scanning.
:::

### Default serializer

Expand Down
1 change: 1 addition & 0 deletions src/Core/src/Eventuous.Persistence/StreamEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ public record struct StreamEvent(
Metadata Metadata,
string ContentType,
long Revision,
DateTime Created = default,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve StreamEvent constructor ABI compatibility

Avoid changing the primary constructor signature of this public record struct in-place: adding Created here changes the generated .ctor from 6 to 7 parameters, so binaries compiled against previous versions will still call the old signature and can fail with MissingMethodException at runtime until they are rebuilt. This is especially problematic for package consumers who upgrade the library without recompiling all dependent assemblies, and it contradicts the “no breaking change” intent.

Useful? React with 👍 / 👎.

bool FromArchive = false
);
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ PersistedEvent AsDocument(NewStreamEvent evt, long position)
(ulong)position + 1,
evt.Payload,
evt.Metadata.ToHeaders(),
DateTime.Now
DateTime.UtcNow
);
}

Expand Down Expand Up @@ -87,7 +87,8 @@ async Task<StreamEvent[]> ReadEvents(Func<QueryContainerDescriptor<PersistedEven
x.Message,
Metadata.FromHeaders(x.Metadata),
x.ContentType,
x.StreamPosition
x.StreamPosition,
x.Created
)
)
.ToArray();
Expand Down
3 changes: 2 additions & 1 deletion src/KurrentDB/src/Eventuous.KurrentDB/KurrentDBEventStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,8 @@ StreamEvent AsStreamEvent(object payload)
payload,
DeserializeMetadata() ?? new Metadata(),
resolvedEvent.Event.ContentType,
resolvedEvent.Event.EventNumber.ToInt64()
resolvedEvent.Event.EventNumber.ToInt64(),
resolvedEvent.Event.Created
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Redis/src/Eventuous.Redis/RedisStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,6 @@ static StreamEvent ToStreamEvent(StreamEntry evt, IEventSerializer serializer, I
};

StreamEvent AsStreamEvent(object payload)
=> new(Guid.Parse(evt[MessageId].ToString()), payload, meta ?? new Metadata(), ContentType, evt.Id.ToLong());
=> new(Guid.Parse(evt[MessageId].ToString()), payload, meta ?? new Metadata(), ContentType, evt.Id.ToLong(), DateTime.Parse(evt[Created]!, CultureInfo.InvariantCulture));
}
}
2 changes: 1 addition & 1 deletion src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
/// <typeparam name="TTransaction">Database transaction type</typeparam>
public abstract class SqlEventStoreBase<TConnection, TTransaction>(IEventSerializer? serializer, IMetadataSerializer? metaSerializer) : IEventStore
where TConnection : DbConnection where TTransaction : DbTransaction {
protected IEventSerializer Serializer { get; } = serializer ?? DefaultEventSerializer.Instance;

Check warning on line 21 in src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs

View workflow job for this annotation

GitHub Actions / Build and test (9.0)

Missing XML comment for publicly visible type or member 'SqlEventStoreBase<TConnection, TTransaction>.Serializer'

Check warning on line 21 in src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs

View workflow job for this annotation

GitHub Actions / Build and test (10.0)

Missing XML comment for publicly visible type or member 'SqlEventStoreBase<TConnection, TTransaction>.Serializer'

Check warning on line 21 in src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs

View workflow job for this annotation

GitHub Actions / Build and test (8.0)

Missing XML comment for publicly visible type or member 'SqlEventStoreBase<TConnection, TTransaction>.Serializer'
protected IMetadataSerializer MetaSerializer { get; } = metaSerializer ?? DefaultMetadataSerializer.Instance;

Check warning on line 22 in src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs

View workflow job for this annotation

GitHub Actions / Build and test (9.0)

Missing XML comment for publicly visible type or member 'SqlEventStoreBase<TConnection, TTransaction>.MetaSerializer'

Check warning on line 22 in src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs

View workflow job for this annotation

GitHub Actions / Build and test (10.0)

Missing XML comment for publicly visible type or member 'SqlEventStoreBase<TConnection, TTransaction>.MetaSerializer'

Check warning on line 22 in src/Relational/src/Eventuous.Sql.Base/SqlEventStoreBase.cs

View workflow job for this annotation

GitHub Actions / Build and test (8.0)

Missing XML comment for publicly visible type or member 'SqlEventStoreBase<TConnection, TTransaction>.MetaSerializer'

const string ContentType = "application/json";

Expand Down Expand Up @@ -144,7 +144,7 @@
_ => throw new("Unknown deserialization result")
};

StreamEvent AsStreamEvent(object payload) => new(evt.MessageId, payload, meta ?? new Metadata(), ContentType, evt.StreamPosition);
StreamEvent AsStreamEvent(object payload) => new(evt.MessageId, payload, meta ?? new Metadata(), ContentType, evt.StreamPosition, evt.Created);
}

/// <inheritdoc />
Expand Down
8 changes: 5 additions & 3 deletions src/Testing/src/Eventuous.Testing/InMemoryEventStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ CancellationToken cancellationToken
) {
var existing = _storage.GetOrAdd(stream, s => new(s));
existing.AppendEvents(expectedVersion, events);
_global.AddRange(events.Select((x, i) => new StreamEvent(x.Id, x.Payload, x.Metadata, "application/json", _global.Count + i)));
var now = DateTime.UtcNow;
_global.AddRange(events.Select((x, i) => new StreamEvent(x.Id, x.Payload, x.Metadata, "application/json", _global.Count + i, now)));

return Task.FromResult(new AppendEventsResult((ulong)(_global.Count - 1), existing.Version));
}
Expand All @@ -33,9 +34,10 @@ public Task<AppendEventsResult[]> AppendEvents(IReadOnlyCollection<NewStreamAppe
var i = 0;

foreach (var append in appends) {
var now = DateTime.UtcNow;
var existing = _storage.GetOrAdd(append.StreamName, s => new(s));
existing.AppendEvents(append.ExpectedVersion, append.Events);
_global.AddRange(append.Events.Select((x, j) => new StreamEvent(x.Id, x.Payload, x.Metadata, "application/json", _global.Count + j)));
_global.AddRange(append.Events.Select((x, j) => new StreamEvent(x.Id, x.Payload, x.Metadata, "application/json", _global.Count + j, now)));
results[i++] = new AppendEventsResult((ulong)(_global.Count - 1), existing.Version);
}

Expand Down Expand Up @@ -97,7 +99,7 @@ public void AppendEvents(ExpectedStreamVersion expectedVersion, IReadOnlyCollect

foreach (var newEvent in events) {
var version = ++Version;
var streamEvent = new StreamEvent(newEvent.Id, newEvent.Payload, newEvent.Metadata, "application/json", version);
var streamEvent = new StreamEvent(newEvent.Id, newEvent.Payload, newEvent.Metadata, "application/json", version, DateTime.UtcNow);
_events.Add(new(streamEvent, version));
}
}
Expand Down
Loading