Azure/durabletask

Durable Orchestration/Activity Creator with Dependency Injection

goneneren opened this issue · 1 comments

I'm using the following DurableObjectCreator class and RegisterWorkflow and RegisterActivity Helper Methods to register workflows and activities with dependency injection.

Wanted to share and get your feedback.

/// <summary>
/// Durable Orchestration/Activity Creator with Dependency Injection
/// This helper class allows services to be injected in Durable Orchestrations and Activities at runtime
/// </summary>
/// <typeparam name="TDurableType">Should be TaskOrchestration or TaskActivity</typeparam>
/// <typeparam name="TInstanceType">Local Instance Type of TaskOrchestration or TaskActivity</typeparam>
public class DurableObjectCreator<TDurableType, TInstanceType> : ObjectCreator<TDurableType>
{
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// Assigns the name and version of the Durable Object and sets the service provider
    /// </summary>
    public DurableObjectCreator(string version, IServiceProvider serviceProvider)
    {
        Name = typeof(TInstanceType).Name;
        Version = version;
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// Returns a new instance of the Durable Type
    /// </summary>
    public override TDurableType Create()
    {
        return (TDurableType)_serviceProvider.GetService(typeof(TInstanceType))!;
    }
}

Helper methods:

public static void RegisterWorkflow<T>(this TaskHubWorker taskHubWorker, string version, IServiceProvider hubServiceProvider)
{
    taskHubWorker.AddTaskOrchestrations(new DurableObjectCreator<TaskOrchestration, T>(version, hubServiceProvider));
}

public static void RegisterActivity<T>(this TaskHubWorker taskHubWorker, string version, IServiceProvider hubServiceProvider)
{
    taskHubWorker.AddTaskActivities(new DurableObjectCreator<TaskActivity, T>(version, hubServiceProvider));
}

Registration becomes:

public static readonly string V1 = "1";

// Register an activity:
taskHubWorker.RegisterActivity<ActivityType>(V1, serviceProvider);

// Register a workflow:
taskHubWorker.RegisterWorkflow<WorkflowType>(V1, serviceProvider);
jviau commented

I have a DI library available here if you want: https://github.com/jviau/durabletask-hosting

The approach you provided is fine, it just lacks broader integration with the hosted model and have to manualy supply IServiceProvider with each call. But if you are fine with that, it is your project/code/solution after all.

Going to close this as there is not anything actionable for the durable team here.