Skip to content

Commit

Permalink
Fix issue with DI-based static async activities (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
cretz authored Jan 5, 2024
1 parent b64dd6d commit 0e592ee
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 17 deletions.
20 changes: 4 additions & 16 deletions src/Temporalio.Extensions.Hosting/ServiceProviderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,27 +60,15 @@ public static ActivityDefinition CreateTemporalActivityDefinition(
// Invoker can be async (i.e. returns Task<object?>)
Func<object?[], Task<object>> invoker = async args =>
{
// If static, just invoke and unwrap exception
if (method.IsStatic)
{
try
{
return method.Invoke(null, args);
}
catch (TargetInvocationException e)
{
ExceptionDispatchInfo.Capture(e.InnerException!).Throw();
// Unreachable
throw new InvalidOperationException("Unreachable");
}
}
// Wrap in a scope
// Wrap in a scope (even for statics to keep logic simple)
using (var scope = provider.CreateScope())
{
object? result;
try
{
result = method.Invoke(scope.ServiceProvider.GetRequiredService(instanceType), args);
// Invoke static or non-static
var instance = method.IsStatic ? null : scope.ServiceProvider.GetRequiredService(instanceType);
result = method.Invoke(instance, args);
}
catch (TargetInvocationException e)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ public DatabaseActivities(DatabaseClient databaseClient) =>
await databaseClient.SelectSomethingAsync(),
await databaseClient.SelectSomethingAsync(),
};

[Activity]
public static async Task<string> DoStaticThingsAsync() => "something-static";
}

[Workflow]
Expand All @@ -54,6 +57,9 @@ public async Task<List<string>> RunAsync()
list.AddRange(await Workflow.ExecuteActivityAsync(
(DatabaseActivities act) => act.DoThingsAsync(),
new() { StartToCloseTimeout = TimeSpan.FromMinutes(5) }));
list.Add(await Workflow.ExecuteActivityAsync(
() => DatabaseActivities.DoStaticThingsAsync(),
new() { StartToCloseTimeout = TimeSpan.FromMinutes(5) }));
return list;
}
}
Expand Down Expand Up @@ -89,7 +95,7 @@ public async Task TemporalWorkerService_ExecuteAsync_SimpleWorker()
new($"wf-{Guid.NewGuid()}", taskQueue));
// Single activity calls use the same client but different calls use different clients
Assert.Equal(
new List<string> { "something-6", "something-7", "something-6", "something-7" },
new List<string> { "something-6", "something-7", "something-6", "something-7", "something-static" },
result);
// Confirm the log appeared
Assert.Contains(loggerFactory.Logs, e => e.Formatted == "Running database workflow");
Expand Down

0 comments on commit 0e592ee

Please sign in to comment.