From 5cefe1457f2eb5a25b02ab65080302dcb626275d Mon Sep 17 00:00:00 2001 From: TekH Date: Thu, 4 Dec 2025 11:48:22 +0100 Subject: [PATCH] Refactor to use scoped services in command handler Updated `InvokeRecActionsCommandHandler` to use `IServiceScopeFactory` for creating scoped services. Replaced direct `IHttpClientFactory` usage with dynamic resolution of `ISender` within a service scope. Improved dependency injection adherence and ensured proper scoping of services. Added `Microsoft.Extensions.DependencyInjection` to `using` directives. --- .../RecActions/Commands/InvokeBatchRecActionsCommand.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/ReC.Application/RecActions/Commands/InvokeBatchRecActionsCommand.cs b/src/ReC.Application/RecActions/Commands/InvokeBatchRecActionsCommand.cs index bfe57ff..2ed4b66 100644 --- a/src/ReC.Application/RecActions/Commands/InvokeBatchRecActionsCommand.cs +++ b/src/ReC.Application/RecActions/Commands/InvokeBatchRecActionsCommand.cs @@ -1,4 +1,5 @@ using MediatR; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ReC.Application.RecActions.Queries; @@ -12,7 +13,7 @@ public static class InvokeBatchRecActionsCommandExtensions => sender.Send(new InvokeBatchRecActionsCommand { ProfileId = profileId }, cancel); } -public class InvokeRecActionsCommandHandler(ISender sender, IHttpClientFactory clientFactory, ILogger? logger = null) : IRequestHandler +public class InvokeRecActionsCommandHandler(ISender sender, IServiceScopeFactory scopeFactory, IHttpClientFactory clientFactory, ILogger? logger = null) : IRequestHandler { public async Task Handle(InvokeBatchRecActionsCommand request, CancellationToken cancel) { @@ -27,7 +28,9 @@ public class InvokeRecActionsCommandHandler(ISender sender, IHttpClientFactory c await semaphore.WaitAsync(cancel); try { - await sender.Send(action.ToInvokeCommand(), cancel); + using var scope = scopeFactory.CreateScope(); + var sender = scope.ServiceProvider.GetRequiredService(); + await sender.Send(action.ToInvokeCommand(), cancel); } catch(Exception ex) {