Simplify InvokeRecActionsCommandHandler dependencies and logic
Refactored InvokeRecActionsCommandHandler to only require ISender, removing IServiceScopeFactory, IHttpClientFactory, and ILogger. Replaced concurrent invocation and error handling with a simple sequential loop, streamlining batch recommendation action execution.
This commit is contained in:
@@ -1,6 +1,4 @@
|
|||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using ReC.Application.RecActions.Queries;
|
using ReC.Application.RecActions.Queries;
|
||||||
|
|
||||||
namespace ReC.Application.RecActions.Commands;
|
namespace ReC.Application.RecActions.Commands;
|
||||||
@@ -13,40 +11,13 @@ public static class InvokeBatchRecActionsCommandExtensions
|
|||||||
=> sender.Send(new InvokeBatchRecActionsCommand { ProfileId = profileId }, cancel);
|
=> sender.Send(new InvokeBatchRecActionsCommand { ProfileId = profileId }, cancel);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class InvokeRecActionsCommandHandler(ISender sender, IServiceScopeFactory scopeFactory, IHttpClientFactory clientFactory, ILogger<InvokeRecActionsCommandHandler>? logger = null) : IRequestHandler<InvokeBatchRecActionsCommand>
|
public class InvokeRecActionsCommandHandler(ISender sender) : IRequestHandler<InvokeBatchRecActionsCommand>
|
||||||
{
|
{
|
||||||
public async Task Handle(InvokeBatchRecActionsCommand request, CancellationToken cancel)
|
public async Task Handle(InvokeBatchRecActionsCommand request, CancellationToken cancel)
|
||||||
{
|
{
|
||||||
var actions = await sender.Send(request.ToReadQuery(q => q.Invoked = false), cancel);
|
var actions = await sender.Send(request.ToReadQuery(q => q.Invoked = false), cancel);
|
||||||
|
|
||||||
var http = clientFactory.CreateClient();
|
foreach (var action in actions)
|
||||||
|
await sender.Send(action.ToInvokeCommand(), cancel);
|
||||||
using var semaphore = new SemaphoreSlim(5);
|
|
||||||
|
|
||||||
var tasks = actions.Select(async action =>
|
|
||||||
{
|
|
||||||
await semaphore.WaitAsync(cancel);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
using var scope = scopeFactory.CreateScope();
|
|
||||||
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
|
|
||||||
await sender.Send(action.ToInvokeCommand(), cancel);
|
|
||||||
}
|
|
||||||
catch(Exception ex)
|
|
||||||
{
|
|
||||||
logger?.LogError(
|
|
||||||
ex,
|
|
||||||
"Error invoking Rec action. ProfileId: {ProfileId}, Id: {Id}",
|
|
||||||
action.ProfileId,
|
|
||||||
action.Id
|
|
||||||
);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
semaphore.Release();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user