title
stringlengths
3
46
content
stringlengths
0
1.6k
18:148
By using events, we may keep the code of each aggregate substantially independent of the code of other aggregates that are involved in the same database transactions: each aggregate generates events that might interest other aggregates, such as a price change in a touristic package aggregate, and all other aggregates that depend on this price subscribe to that event, so they can update their data coherently. This way, when a new aggregate that depends on the tourist package price is added during system maintenance, we don’t need to modify the tourist package aggregate.
18:149
When the event might also interest other microservices, the event is also passed to a message broker, which makes the event also available for subscription to code in other microservices. Message brokers were discussed in Chapter 14, Implementing Microservices with .NET.
18:150
Below is an example event definition:
18:151
public class PackagePriceChangedEvent: IEventNotification
18:152
{
18:153
public PackagePriceChangedEvent(int id, decimal price,
18:154
long oldVersion, long newVersion)
18:155
{
18:156
PackageId = id;
18:157
NewPrice = price;
18:158
OldVersion = oldVersion;
18:159
NewVersion = newVersion;
18:160
}
18:161
public int PackageId { get; }
18:162
public decimal NewPrice { get; }
18:163
public long OldVersion { get; }
18:164
public long NewVersion { get; }
18:165
}
18:166
18:167
When an aggregate sends all its changes to another microservice, it should have a version property. The microservice that receives the changes uses this version property to apply all changes in the right order. An explicit version number is necessary because changes are sent asynchronously, so the order in which they are received may differ from the order in which they were sent. For this purpose, events that are used to publish changes outside of the application have both OldVersion (the version before the change) and NewVersion (the version after the change) properties. Events associated with delete events have no NewVersion since, after being deleted, an entity can’t store any versions.
18:168
The next subsection explains how all interfaces defined in the domain layer are implemented in the data layer.
18:169
Defining the domain layer implementation
18:170
The domain layer implementation contains the implementation of all repository interfaces and aggregate interfaces defined in the domain layer interface. In the case of .NET 8, it uses Entity Framework Core entities to implement aggregates. Adding a domain layer interface in between the domain layer’s actual implementation and the application layer decouples the application layer from EF and entity-specific details. Moreover, it conforms with the onion architecture, which, in turn, is an advised way to architect microservices.
18:171
The domain layer implementation project should contain references to Microsoft.AspNetCore.Identity.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer NuGet packages, since we are using Entity Framework Core with SQL Server. It references Microsoft.EntityFrameworkCore.Tools and Microsoft.EntityFrameworkCore.Design, which is needed to generate database migrations, as explained in the Entity Framework Core migrations section of Chapter 13, Interacting with Data in C# – Entity Framework Core.
18:172
We should have a Models folder that contains all database entities. They are similar to the ones in Chapter 13. The only differences are as follows:
18:173
18:174
They inherit from Entity<T>, which contains all the basic features of aggregates. Please note that inheriting from Entity<T> is only needed for aggregate roots; all other entities must be defined as explained in Chapter 13.
18:175
They have no Id since it is inherited from Entity<T>.
18:176
Some of them might have an EntityVersion property decorated with the [ConcurrencyCheck] attribute. It contains the entity version that is needed to send changes to other microservices. The ConcurrencyCheck attribute is needed to prevent concurrency errors while updating the entity version. This prevents suffering the performance penalty implied by a transaction.
18:177
18:178
More specifically, when saving entity changes, if the value of a field marked with the ConcurrencyCheck attribute is different from the one that was read when the entity was loaded in memory, a concurrency exception is thrown to inform the calling method that someone else modified this value after the entity was read, but before we attempted to save its changes. This way, the calling method can repeat the whole operation with the hope that this time, no one will write the same entity in the database during its execution.
18:179
It is worth analyzing an example entity:
18:180
public class Package: Entity<int>, IPackage
18:181
{
18:182
public void FullUpdate(IPackageFullEditDTO o)
18:183
{
18:184
if (IsTransient())
18:185
{
18:186
Id = o.Id;
18:187
DestinationId = o.DestinationId;
18:188
}
18:189
else
18:190
{
18:191
if (o.Price != this.Price)
18:192
this.AddDomainEvent(new PackagePriceChangedEvent(
18:193
Id, o.Price, EntityVersion, EntityVersion+1));
18:194
}
18:195
Name = o.Name;
18:196
Description = o.Description;
18:197
Price = o.Price;
18:198
DurationInDays = o.DurationInDays;
18:199
StartValidityDate = o.StartValidityDate;
18:200
EndValidityDate = o.EndValidityDate;
18:201
}
18:202
[MaxLength(128)]
18:203
public string Name { get; set; }
18:204
[MaxLength(128)]
18:205
public string? Description { get; set; }
18:206
public decimal Price { get; set; }
18:207
public int DurationInDays { get; set; }
18:208
public DateTime? StartValidityDate { get; set; }
18:209
public DateTime? EndValidityDate { get; set; }
18:210
public Destination MyDestination { get; set; }
18:211
[ConcurrencyCheck]
18:212
public long EntityVersion{ get; set; }
18:213
public int DestinationId { get; set; }
18:214
}
18:215
18:216
The FullUpdate method is the only way to update the IPackage aggregate. When the price changes, it adds a PackagePriceChangedEvent to the entity list of events.
18:217
MainDBContext implements IUnitOfWork. The following code shows the implementation of all methods that start, rollback, and commit a transaction:
18:218
public async Task StartAsync()
18:219
{
18:220
await Database.BeginTransactionAsync();
18:221
}
18:222
public Task CommitAsync()
18:223
{
18:224
Database.CommitTransaction();
18:225
return Task.CompletedTask;
18:226
}
18:227
public Task RollbackAsync()
18:228
{
18:229
Database.RollbackTransaction();
18:230
return Task.CompletedTask;
18:231
}
18:232
18:233
However, they are rarely used by command classes in a distributed environment. In fact, like distributed transactions, local database-blocking transactions are also avoided because they might block database resources for too much time, which is incompatible with the maximization of traffic typical of microservices-based applications.
18:234
Likely, as already mentioned, all databases support tagging some row fields as concurrency checks. In Entity Framework Core, this is done by decorating the entity property corresponding to the field with the ConcurrencyCheck attribute.
18:235
Concurrency checks detect interferences of another transaction, B, on a record while performing transaction A. This way, we can perform transaction A without blocking any database record or table, and if we detect interference, we abort transaction A and retry it till it succeeds without interference. This technique works well if transactions are very quick and, consequently, interferences are rare.
18:236
More specifically, if during transaction A, the value of the concurrency checks specified by an update operation differs from the one stored in the record being updated, the update is aborted, and a concurrency exception is thrown. The rationale is that another transaction, B, modified the concurrency check, thus interfering with the operation being performed by A.
18:237
Accordingly, the method that passes all changes applied to DbContext to the database performs a check for concurrency exceptions:
18:238
public async Task<bool> SaveEntitiesAsync()
18:239
{
18:240
try
18:241
{
18:242
return await SaveChangesAsync() > 0;
18:243
}
18:244
catch (DbUpdateConcurrencyException ex)
18:245
{
18:246
foreach (var entry in ex.Entries)
18:247
{