title
stringlengths
3
46
content
stringlengths
0
1.6k
21:1225
Id = o.Id;
21:1226
DestinationId = o.DestinationId;
21:1227
}
21:1228
else
21:1229
{
21:1230
if (o.Price != this.Price)
21:1231
this.AddDomainEvent(new PackagePriceChangedEvent(
21:1232
Id, o.Price, EntityVersion, EntityVersion+1));
21:1233
}
21:1234
Name = o.Name;
21:1235
Description = o.Description;
21:1236
Price = o.Price;
21:1237
DurationInDays = o.DurationInDays;
21:1238
StartValidityDate = o.StartValidityDate;
21:1239
EndValidityDate = o.EndValidityDate;
21:1240
}
21:1241
[MaxLength(128)]
21:1242
public string Name { get; set; }= null!;
21:1243
[MaxLength(128)]
21:1244
public string? Description { get; set; }
21:1245
public decimal Price { get; set; }
21:1246
public int DurationInDays { get; set; }
21:1247
public DateTime? StartValidityDate { get; set; }
21:1248
public DateTime? EndValidityDate { get; set; }
21:1249
public Destination MyDestination { get; set; }= null!;
21:1250
[ConcurrencyCheck]
21:1251
public long EntityVersion{ get; set; }
21:1252
public int DestinationId { get; set; }
21:1253
}
21:1254
21:1255
The FullUpdate method is the only way to update the IPackage aggregate. When the price changes, add PackagePriceChangedEvent to the entity list of events.
21:1256
The MainDBContext.cs file contains the database context definition. It doesn’t inherit from DbContext but from the following predefined context class:
21:1257
IdentityDbContext<IdentityUser<int>, IdentityRole<int>, int>
21:1258
21:1259
This context defines the user’s tables needed for the authentication. In our case, we opted for the IdentityUser<T> standard and IdentityRole<S> for users and roles, respectively, and used integers for both the T and S entity keys. However, we may also use classes that inherit from IdentityUser and IdentityRole and then add further properties.
21:1260
In the OnModelCreating method, we must call base.OnModelCreating(builder) in order to apply the configuration defined in IdentityDbContext.
21:1261
MainDBContext implements IUnitOfWork. The following code shows the implementation of all methods that start, roll back, and commit a transaction:
21:1262
public async Task StartAsync()
21:1263
{
21:1264
await Database.BeginTransactionAsync();
21:1265
}
21:1266
public Task CommitAsync()
21:1267
{
21:1268
Database.CommitTransaction();
21:1269
return Task.CompletedTask;
21:1270
}
21:1271
public Task RollbackAsync()
21:1272
{
21:1273
Database.RollbackTransaction();
21:1274
return Task.CompletedTask;
21:1275
}
21:1276
21:1277
However, they are rarely used by command classes in a distributed environment. This is because retrying the same operation until no concurrency exception is returned usually ensures better performance than transactions.
21:1278
It is worth analyzing the implementation of the method that passes all changes applied to DbContext to the database:
21:1279
public async Task<bool> SaveEntitiesAsync()
21:1280
{
21:1281
try
21:1282
{
21:1283
return await SaveChangesAsync() > 0;
21:1284
}
21:1285
catch (DbUpdateConcurrencyException ex)
21:1286
{
21:1287
foreach (var entry in ex.Entries)
21:1288
{
21:1289
entry.State = EntityState.Detached;
21:1290
21:1291
}
21:1292
throw;
21:1293
}
21:1294
}
21:1295
21:1296
The preceding implementation just calls the SaveChangesAsync DbContext context method, which saves all changes to the database, but then it intercepts all concurrency exceptions and detaches all the entities involved in the concurrency error from the context. This way, the next time a command retries the whole failed operation, their updated versions will be reloaded from the database.
21:1297
The Repositories folder contains all repository implementations. It is worth analyzing the implementation of the IPackageRepository.Delete method:
21:1298
public async Task<IPackage?> Delete(int id)
21:1299
{
21:1300
var model = await GetAsync(id);
21:1301
if (model is not Package package) return null;
21:1302
context.Packages.Remove(package);
21:1303
model.AddDomainEvent(
21:1304
new PackageDeleteEvent(
21:1305
model.Id, package.EntityVersion));
21:1306
return model;
21:1307
}
21:1308
21:1309
It reads the entity from the database and formally removes it from the Packages dataset. This will force the entity to be deleted from the database when changes are saved to the database. Moreover, it adds PackageDeleteEvent to the aggregate list of events.
21:1310
The Extensions folder contains the DBExtensions static class, which, in turn, defines two extension methods to be added to the application DI engine and the ASP.NET Core pipeline, respectively. Once added to the pipeline, these two methods will connect the database layer to the application layer.
21:1311
The IServiceCollection extension of AddDbLayer accepts (as its input parameters) the database connection string and the name of the .dll file that contains all migrations. Then, it does the following:
21:1312
services.AddDbContext<MainDbContext>(options =>
21:1313
options.UseSqlServer(connectionString,
21:1314
b => b.MigrationsAssembly(migrationAssembly)));
21:1315
21:1316
That is, it adds the database context to the DI engine and defines its options – namely, that it uses SQL Server, the database connection string, and the name of the .dll file that contains all migrations.
21:1317
Then, it does the following:
21:1318
services.AddIdentity<IdentityUser<int>, IdentityRole<int>>()
21:1319
.AddEntityFrameworkStores<MainDbContext>()
21:1320
.AddDefaultTokenProviders();
21:1321
21:1322
That is, it adds and configures all the types needed to handle database-based authentication and authorization. It adds UserManager, which the application layer can use to manage users. AddDefaultTokenProviders adds the provider that creates the authentication tokens using data contained in the database when users log in.
21:1323
Finally, it discovers and adds to the DI engine all repository implementations by calling the AddAllRepositories method, which is defined in the DDD tools we added to the domain layer project.
21:1324
The UseDBLayer extension method ensures migrations are applied to the database by calling context.Database.Migrate(), and then it populates the database with some initial objects. In our case, it uses RoleManager and UserManager to create an administrative role and an initial administrator, respectively. Then, it creates some sample destinations and packages.