diff --git a/src/Autofac/Core/Lifetime/LifetimeScope.cs b/src/Autofac/Core/Lifetime/LifetimeScope.cs index 276fe5845..7f391d5bf 100644 --- a/src/Autofac/Core/Lifetime/LifetimeScope.cs +++ b/src/Autofac/Core/Lifetime/LifetimeScope.cs @@ -24,6 +24,7 @@ // OTHER DEALINGS IN THE SOFTWARE. using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -47,7 +48,7 @@ public class LifetimeScope : Disposable, ISharingLifetimeScope, IServiceProvider /// Protects shared instances from concurrent access. Other members and the base class are threadsafe. /// private readonly object _synchRoot = new object(); - private readonly IDictionary _sharedInstances = new Dictionary(); + private readonly ConcurrentDictionary _sharedInstances = new ConcurrentDictionary(); private readonly ISharingLifetimeScope _parent; @@ -302,20 +303,23 @@ public object GetOrCreateAndShare(Guid id, Func creator) { if (creator == null) throw new ArgumentNullException(nameof(creator)); - lock (_synchRoot) + object result; + if (!_sharedInstances.TryGetValue(id, out result)) { - object result; - if (!_sharedInstances.TryGetValue(id, out result)) + lock (_synchRoot) { - result = creator(); - if (_sharedInstances.ContainsKey(id)) - throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, LifetimeScopeResources.SelfConstructingDependencyDetected, result.GetType().FullName)); - - _sharedInstances.Add(id, result); + if (!_sharedInstances.TryGetValue(id, out result)) + { + result = creator(); + if (_sharedInstances.ContainsKey(id)) + throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, LifetimeScopeResources.SelfConstructingDependencyDetected, result.GetType().FullName)); + + _sharedInstances.TryAdd(id, result); + } } - - return result; } + + return result; } ///