Search code examples
elsa-workflows

Store Workflow Activity Data When Publishing


I Need to store a specific activity data in another collection in database whenever a user publish a workflow in elsa.

I dont find any documentation, Please suggest me some resource or suggestion to achieve this. I have try to implement this with middleware. The Middleware code is

namespace WorkFlowV3
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        static HttpClient client = new HttpClient();
        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            //Write Custom Logic Here....
            client.BaseAddress = new Uri("#");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            string path = "/api/test-middleware-call";
            HttpResponseMessage response = await client.GetAsync(path);

            await _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}

But in this process, I cant fetch the specific activity data.


Solution

  • The easiest way to store information in your own DB in response to the "workflow published" event is by implementing a notification handler (from MediatR) that handles the WorkflowDefinitionPublished notification.

    For example:

    public class MyWorkflowPublishedhandler : INotificationhandler<WorkflowDefinitionPublished>
    {
       private readonly IMyDatabaseStore _someRepository;
    
    
       public MyWorkflowPublishedhandler(IMyDatabaseStore someRepository)
       {
          _someRepository = someRepository;
       }
    
       public async Task Handle(WorkflowDefinitionPublished notification, CancellationToken cancellationToken)
       {
          var workflowDefinition = notification.WorkflowDefinition;
    
         // Your logic to do a thing.
       }
    
    }
    

    To register this handler, from your Startup or Program class, add the following code:

    services.AddNotificationHandler<MyWorkflowPublishedhandler>();
    

    Your handler will be invoked every time a workflow gets published.