Skip to content

Commit

Permalink
Add ServiceProviderAccessor to allow access to IServiceProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
tdg5 committed Nov 5, 2024
1 parent 46410a6 commit 6b175cf
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Temporalio.Extensions.Hosting/IServiceProviderAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;

namespace Temporalio.Extensions.Hosting
{
/// <summary>
/// Provides access to the current, scoped <see cref="IServiceProvider"/> if
/// one is available.
/// </summary>
public interface IServiceProviderAccessor
{
/// <summary>
/// Gets or sets the current service provider.
/// </summary>
IServiceProvider? ServiceProvider { get; set; }
}
}
42 changes: 42 additions & 0 deletions src/Temporalio.Extensions.Hosting/ServiceProviderAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;
using System.Threading;

namespace Temporalio.Extensions.Hosting
{
/// <summary>
/// Provides an implementation of <see cref="IServiceProvider" /> based on
/// the current execution context.
/// </summary>
public class ServiceProviderAccessor : IServiceProviderAccessor
{
private static readonly AsyncLocal<ServiceProviderHolder> ServiceProviderCurrent = new();

/// <inheritdoc/>
public IServiceProvider? ServiceProvider
{
get => ServiceProviderCurrent.Value?.ServiceProvider;

set
{
var holder = ServiceProviderCurrent.Value;
if (holder != null)
{
// Clear current IServiceProvider trapped in the AsyncLocals, as its done.
holder.ServiceProvider = null;
}

if (value != null)
{
// Use an object indirection to hold the IServiceProvider in the AsyncLocal,
// so it can be cleared in all ExecutionContexts when its cleared.
ServiceProviderCurrent.Value = new ServiceProviderHolder { ServiceProvider = value };
}
}
}

private sealed class ServiceProviderHolder
{
public IServiceProvider? ServiceProvider { get; set; }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ public static ActivityDefinition CreateTemporalActivityDefinition(
#else
var scope = provider.CreateScope();
#endif
if (scope.ServiceProvider.GetService<IServiceProviderAccessor>() is IServiceProviderAccessor accessor)
{
accessor.ServiceProvider = scope.ServiceProvider;
}
try
{
object? result;
Expand Down Expand Up @@ -112,6 +116,10 @@ public static ActivityDefinition CreateTemporalActivityDefinition(
finally
{
#if NET6_0_OR_GREATER
if (scope.ServiceProvider.GetService<IServiceProviderAccessor>() is IServiceProviderAccessor accessor)
{
accessor.ServiceProvider = null;
}
await scope.DisposeAsync().ConfigureAwait(false);
#else
scope.Dispose();
Expand Down

0 comments on commit 6b175cf

Please sign in to comment.