title
stringlengths
3
46
content
stringlengths
0
1.6k
18:248
entry.State = EntityState.Detached;
18:249
18:250
}
18:251
throw;
18:252
}
18:253
}
18:254
18:255
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.
18:256
In other words, when the update fails because of the interference of transaction B, we allow the interfering transaction B to complete its process. Then, EF automatically reloads all entities modified by B that contain the value of the concurrency check modified by B. This way, when the operation is retried, if no other transaction interferes, there will be no conflict on the concurrency check.
18:257
The practical usage of concurrency checks is detailed in the A frontend microservice example of Chapter 21, Case Study.
18:258
All repository implementations are defined in a Repositories folder to ensure better maintainability.
18:259
Finally, all repositories are automatically discovered and added to the application DI engine, calling the AddAllRepositories method, which is defined in the DDD tools we added to the domain layer project. More details on how to ensure this method is called when the application starts are given in the example detailed description in the A frontend microservice section of Chapter 21, Case Study.
18:260
Defining the application layer
18:261
The application layer contains the definition of all business operations. These business operations use data provided by the user to modify domain layer abstraction aggregates, such as touristic packages. When all business operations involved in the current user request have been performed, an IUnitOfWork.SaveEntitiesAsync() operation is performed to save all changes to the database.
18:262
As a first step, for simplicity, let’s freeze the application culture to en-US by adding the following code to the ASP.NET Core pipeline:
18:263
app.UseAuthorization();
18:264
// Code to add: configure the Localization middleware
18:265
var ci = new CultureInfo(`en-US`);
18:266
app.UseRequestLocalization(new RequestLocalizationOptions
18:267
{
18:268
DefaultRequestCulture = new RequestCulture(ci),
18:269
SupportedCultures = new List<CultureInfo>
18:270
{
18:271
ci,
18:272
},
18:273
SupportedUICultures = new List<CultureInfo>
18:274
{
18:275
ci,
18:276
}
18:277
});
18:278
18:279
As a second step, we can create a Tools folder to place the ApplicationLayer code, which you can find in the ch7 code of the GitHub repository associated with this book. With these tools in place, in Program.cs, we can add the code that automatically discovers and adds all queries, command handlers, and event handlers to the DI engine, as shown here:
18:280
...
18:281
...
18:282
builder.Services.AddAllQueries(this.GetType().Assembly);
18:283
builder.Services.AddAllCommandHandlers(this.GetType().Assembly);
18:284
builder.Services.AddAllEventHandlers(this.GetType().Assembly);
18:285
18:286
Then, we must add a Queries folder to place all queries and their associated interfaces. As an example, let’s have a look at the query that lists all packages:
18:287
public class PackagesListQuery:IPackagesListQuery
18:288
{
18:289
private readonly MainDbContext ctx;
18:290
public PackagesListQuery(MainDbContext ctx)
18:291
{
18:292
this.ctx = ctx;
18:293
}
18:294
public async Task<IReadOnlyCollection<PackageInfosViewModel>> GetAllPackages()
18:295
{
18:296
return await ctx.Packages.Select(m => new PackageInfosViewModel
18:297
{
18:298
StartValidityDate = m.StartValidityDate,
18:299
...
18:300
})
18:301
.OrderByDescending(m=> m.EndValidityDate)
18:302
.ToListAsync();
18:303
}
18:304
}
18:305
18:306
The query object is automatically injected into the application DB context. The GetAllPackages method uses LINQ to project all of the required information into PackageInfosViewModel and sorts all results in descending order on the EndValidityDate property.
18:307
The Commands folder contains all commands. As an example, let’s have a look at the command used to modify packages:
18:308
public class UpdatePackageCommand: ICommand
18:309
{
18:310
public UpdatePackageCommand(IPackageFullEditDTO updates)
18:311
{
18:312
Updates = updates;
18:313
}
18:314
public IPackageFullEditDTO Updates { get; private set; }
18:315
}
18:316
18:317
Command handlers can be placed in the Handlers folder. It is worth analyzing the command that updates packages:
18:318
private readonly IPackageRepository repo;
18:319
private readonly IEventMediator mediator;
18:320
public UpdatePackageCommandHandler(IPackageRepository repo, IEventMediator mediator)
18:321
{
18:322
this.repo = repo;
18:323
this.mediator = mediator;
18:324
}
18:325
18:326
Its constructor has automatically injected the IPackageRepository repository and an IEventMediator instance needed to trigger event handlers. The following code also shows the implementation of the standard HandleAsync command handler method:
18:327
public async Task HandleAsync(UpdatePackageCommand command)
18:328
{
18:329
bool done = false;
18:330
IPackage model;
18:331
while (!done)
18:332
{
18:333
try
18:334
{
18:335
model = await repo.Get(command.Updates.Id);
18:336
if (model == null) return;
18:337
model.FullUpdate(command.Updates);
18:338
await mediator.TriggerEvents(model.DomainEvents);
18:339
await repo.UnitOfWork.SaveEntitiesAsync();
18:340
done = true;
18:341
}
18:342
catch (DbUpdateConcurrencyException)
18:343
{
18:344
// add some logging here
18:345
}
18:346
}
18:347
}