title
stringlengths
3
46
content
stringlengths
0
1.6k
21:424
{
21:426
this.queue = queue;
21:427
}
21:428
public override async Task<CountingReply> Count(CountingRequest request,
21:429
ServerCallContext context)
21:430
{
21:431
await queue.Enqueue(new GrpcMicroServiceStore.Models.QueueItem
21:432
{
21:433
Cost = request.Cost,
21:434
MessageId = Guid.Parse(request.Id),
21:435
Location = request.Location,
21:436
PurchaseTime = request.PurchaseTime.ToDateTimeOffset(),
21:437
Time = request.Time.ToDateTimeOffset()
21:438
});
21:439
return new CountingReply { };
21:440
}
21:441
}
21:442
21:443
The actual service that receives the purchase messages inherits from the Counter.CounterBase abstract class created by the code generator from the counting.proto file. It receives the database layer interface IMessageQueue using dependency injection and overrides the abstract Count method inherited from Counter.CounterBase. Then, Count uses IMessageQueue to enqueue each received message.
21:444
Before compiling, a few other steps are necessary:
21:445
21:446
We must add a reference to the database-layer GrpcMicroServiceStore project.
21:447
We must add the database connection string to the appsettings.json setting file:
21:448
`ConnectionStrings`: {
21:449
`DefaultConnection`: `Server=(localdb)mssqllocaldb;Database=grpcmicroservice;Trusted_Connection=True;MultipleActiveResultSets=true`
21:450
}
21:451
21:452
21:453
We must add all the necessary database-layer interfaces to the dependency injection by calling the AddStorage database layer extension method:
21:454
builder.Services.AddStorage(
21:455
builder.Configuration.GetConnectionString(`DefaultConnection`));
21:456
21:457
21:458
In Program.cs, we must remove the declaration of the gRPC service scaffolded by Visual Studio, and we must replace it with:
21:459
app.MapGrpcService<CounterService>();
21:460
21:461
21:462
21:463
At this point, compilation should succeed. Having completed the application-layer infrastructure, we can move to the hosted service that performs the actual queue processing.
21:464
Processing the queued requests
21:465
The actual request processing is performed by a worker-hosted service that runs in parallel with the ASP.NET Core pipeline. It is implemented with the hosted services we discussed in the Using generic hosts section of Chapter 11, Applying a Microservice Architecture to Your Enterprise Application. It is worth recalling that hosted services are implementations of the IHostedService interface defined in the dependency injection engine as follows:
21:466
builder.Services.AddHostedService<MyHostedService>();
21:467
21:468
We already described how to implement hosted services for the implementation of ASP.NET Core-based worker microservices in the Implementing worker microservices with ASP.NET Core section of Chapter 14, Implementing Microservices with .NET.
21:469
Below, we repeat the whole code with all details that are specific to our example. The hosted service is defined in the ProcessPurchases.cs file placed in the HostedServices folder:
21:470
using GrpcMicroServiceStore;
21:471
using GrpcMicroServiceStore.Models;
21:472
namespace GrpcMicroService.HostedServices;
21:473
public class ProcessPurchases : BackgroundService
21:474
{
21:475
IServiceProvider services;
21:476
public ProcessPurchases(IServiceProvider services)
21:477
{
21:478
this.services = services;
21:479
}
21:480
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
21:481
{
21:482
bool queueEmpty = false;
21:483
while (!stoppingToken.IsCancellationRequested)
21:484
{
21:485
while (!queueEmpty && !stoppingToken.IsCancellationRequested)
21:486
{
21:487
...
21:488
}
21:489
await Task.Delay(100, stoppingToken);
21:490
queueEmpty = false;
21:491
}
21:492
}
21:493
}
21:494
21:495
Below is the content of the inner loop:
21:496
using (var scope = services.CreateScope())
21:497
{
21:498
IMessageQueue queue = scope.ServiceProvider.GetRequiredService<IMessageQueue>();
21:499
21:500
var toProcess = await queue.Top(10);
21:501
if (toProcess.Count > 0)
21:502
{
21:503
Task<QueueItem?>[] tasks = new Task<QueueItem?>[toProcess.Count];
21:504
for (int i = 0; i < tasks.Length; i++)
21:505
{
21:506
var toExecute = ...
21:507
tasks[i] = toExecute();
21:508
}
21:509
await Task.WhenAll(tasks);
21:510
await queue.Dequeue(tasks.Select(m => m.Result)
21:511
.Where(m => m != null).OfType<QueueItem>());
21:512
}
21:513
else queueEmpty = true;
21:514
}
21:515
21:516
The above code was already explained in the Implementing worker microservices with ASP.NET Core section of Chapter 14, Implementing Microservices with .NET. Therefore, here, we will analyze just the toExecute lambda that is specific to our example:
21:517
var toExecute = async () =>
21:518
{
21:519
using (var sc = services.CreateScope())
21:520
{
21:521
IDayStatistics statistics = sc.ServiceProvider.GetRequiredService<IDayStatistics>();
21:522
return await statistics.Add(toProcess[i]);
21:523
}
21:524
};