Skip to content

Commit

Permalink
Refactor Worker to use IServiceScopeFactory for dependency resolution
Browse files Browse the repository at this point in the history
Refactored the Worker class to use IServiceScopeFactory for DI instead of directly injecting IWorkflowInbox. This enhances the flexibility and lifecycle management of the dependencies.
  • Loading branch information
sfmskywalker committed Sep 19, 2024
1 parent a9e8233 commit 426fb52
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/modules/Elsa.AzureServiceBus/Services/Worker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Elsa.Workflows.Helpers;
using Elsa.Workflows.Runtime.Contracts;
using Elsa.Workflows.Runtime.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Elsa.AzureServiceBus.Services;
Expand All @@ -15,18 +16,18 @@ namespace Elsa.AzureServiceBus.Services;
public class Worker : IAsyncDisposable
{
private readonly ServiceBusProcessor _processor;
private readonly IWorkflowInbox _workflowInbox;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger _logger;
private int _refCount = 1;

/// <summary>
/// Initializes a new instance of the <see cref="Worker"/> class.
/// </summary>
public Worker(string queueOrTopic, string? subscription, ServiceBusClient client, IWorkflowInbox workflowInbox, ILogger<Worker> logger)
public Worker(string queueOrTopic, string? subscription, ServiceBusClient client, IServiceScopeFactory scopeFactory, ILogger<Worker> logger)
{
QueueOrTopic = queueOrTopic;
Subscription = subscription == "" ? default : subscription;
_workflowInbox = workflowInbox;
_scopeFactory = scopeFactory;
_logger = logger;

var options = new ServiceBusProcessorOptions();
Expand Down Expand Up @@ -98,8 +99,10 @@ private async Task InvokeWorkflowsAsync(ServiceBusReceivedMessage message, Cance
var messageModel = CreateMessageModel(message);
var input = new Dictionary<string, object> { [MessageReceived.InputKey] = messageModel };
var activityTypeName = ActivityTypeNameHelper.GenerateTypeName<MessageReceived>();
await using var scope = _scopeFactory.CreateAsyncScope();
var workflowInbox = scope.ServiceProvider.GetRequiredService<IWorkflowInbox>();

var results = await _workflowInbox.SubmitAsync(new NewWorkflowInboxMessage
var results = await workflowInbox.SubmitAsync(new NewWorkflowInboxMessage
{
ActivityTypeName = activityTypeName,
BookmarkPayload = payload,
Expand Down

0 comments on commit 426fb52

Please sign in to comment.