Skip to content

Commit 7fd035c

Browse files
committed
Ensure the DI scope flows through async calls
1 parent a461f56 commit 7fd035c

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the MIT License. See License.txt in the project root for license information.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using System.Threading;
8+
using System.Threading.Tasks;
9+
using DryIoc;
10+
11+
namespace Microsoft.Azure.WebJobs.Script.WebHost.DependencyInjection.DryIoc
12+
{
13+
public class AsyncScopeContext : IScopeContext
14+
{
15+
private static AsyncLocal<IScope> _asyncLocalScope = new AsyncLocal<IScope>();
16+
17+
public IScope GetCurrentOrDefault()
18+
{
19+
return _asyncLocalScope.Value;
20+
}
21+
22+
public IScope SetCurrent(SetCurrentScopeHandler setCurrentScope)
23+
{
24+
if (setCurrentScope == null)
25+
{
26+
throw new ArgumentNullException(nameof(setCurrentScope));
27+
}
28+
29+
var oldScope = GetCurrentOrDefault();
30+
var newScope = setCurrentScope(oldScope);
31+
_asyncLocalScope.Value = newScope;
32+
return newScope;
33+
}
34+
35+
public void Dispose()
36+
{
37+
}
38+
}
39+
}

src/WebJobs.Script.WebHost/DependencyInjection/DryIoc/Container.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ namespace DryIoc
3434
using System.Text;
3535
using System.Threading;
3636
using System.Diagnostics.CodeAnalysis; // for SuppressMessage
37-
using System.Diagnostics; // for StackTrace
3837

3938
using ImTools;
4039
using static ImTools.ArrayTools;
@@ -64,6 +63,7 @@ namespace DryIoc
6463
using NewArrayExpr = System.Linq.Expressions.NewArrayExpression;
6564
using MemberAssignmentExpr = System.Linq.Expressions.MemberAssignment;
6665
using FactoryDelegateExpr = System.Linq.Expressions.Expression<FactoryDelegate>;
66+
using global::Microsoft.Azure.WebJobs.Script.WebHost.DependencyInjection.DryIoc;
6767

6868
#endif
6969

@@ -1942,7 +1942,7 @@ private Container(Rules rules, Ref<Registry> registry, IScope singletonScope,
19421942
_registry = registry;
19431943

19441944
_singletonScope = singletonScope;
1945-
_scopeContext = scopeContext;
1945+
_scopeContext = scopeContext ?? new AsyncScopeContext();
19461946
_ownCurrentScope = ownCurrentScope;
19471947

19481948
_disposed = disposed;

0 commit comments

Comments
 (0)