Ensure uniqueness of workflows by instance Id #5746
-
Hello, Is there a way to ensure that only one workflow with a given InstanceId is ever created? Currently if I call Is there a way to prevent the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
To ensure that only one workflow with a given InstanceId is ever created, you can use the Here's an example of how you might implement this check: var instanceId = "myUniqueInstanceId"; // The unique instance ID you want to check for
var workflowDefinitionId = "yourWorkflowDefinitionId"; // The definition ID of the workflow
// Get the IWorkflowInstanceStore service
var workflowInstanceStore = serviceProvider.GetRequiredService<IWorkflowInstanceStore>();
// Setup query specification
var specification = new WorkflowInstanceSpecification().WithWorkflowDefinitionId(workflowDefinitionId).WithWorkflowInstanceId(instanceId);
// Count matching results
var existingInstanceCount = await workflowInstanceStore.CountAsync(specification);
if (existingInstanceCount == 0)
{
// No existing workflow instance found, safe to start a new one
var workflowRuntime = serviceProvider.GetRequiredService<IWorkflowRuntime>();
await workflowRuntime.StartWorkflowAsync(definitionId, new StartWorkflowRuntimeOptions { InstanceId = myUniqueInstanceId });
}
else
{
// A workflow with the specified InstanceId already exists
// Handle this case as needed (e.g., return an error, do nothing, etc.)
} Please note that the If you are using Elsa 2.x or later, you can also consider using the Remember to handle concurrency issues that may arise if multiple requests try to start a workflow with the same InstanceId simultaneously. This comment was generated by Glime. |
Beta Was this translation helpful? Give feedback.
-
Can I use an IActivationStrategy in my workflow definition to achieve this? |
Beta Was this translation helpful? Give feedback.
You can implement interface
IWorkflowActivationStrategy
, and then use your custom implementation in your workflow by callingbuilder.WithActivationStrategyType<MyCustomActivationStrategy>()
when you override methodWorkflowBase.Build(IWorkflowBuilder builder)
.This way, when calling
IWorkflowRuntime.CanStartWorkflowAsync(string definitionId, StartWorkflowRuntimeParams? options = default)
, the activation strategy you configured will be used to determine whether the workflow can be started or not.