Skip to content

Commit

Permalink
Fix #1073 - Check if the ServiceRegistrationInfo is both initalized a…
Browse files Browse the repository at this point in the history
…nd contains implementations before considering it safe to use outside of the lock in DefaultRegisteredServicesTracker
  • Loading branch information
alexmg committed Feb 1, 2020
1 parent 9e07e7a commit cf3674a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,8 @@ private ServiceRegistrationInfo GetServiceInfo(Service service)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ServiceRegistrationInfo? GetInitializedServiceInfoOrDefault(Service service)
{
if (_serviceInfo.TryGetValue(service, out var existing) && existing.IsInitialized)
// Issue #1073: Check if any implementations are available in addition to being initialized to avoid coarse grain locking.
if (_serviceInfo.TryGetValue(service, out var existing) && existing.IsInitialized && existing.Implementations.Any())
return existing;

return null;
Expand Down
13 changes: 13 additions & 0 deletions test/Autofac.Test/Concurrency/ConcurrencyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Autofac.Features.ResolveAnything;
using Xunit;

namespace Autofac.Test.Concurrency
Expand Down Expand Up @@ -132,6 +133,18 @@ public void WhenTwoThreadsInitialiseASharedInstanceSimultaneouslyViaChildLifetim
Assert.Single(results.Distinct());
}

[Fact]
public void WhenSeveralThreadsResolveNotAlreadyRegisteredType_DoesNotThrow()
{
for (var i = 0; i < 20_000; i++)
{
var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
var container = builder.Build();
Parallel.Invoke(() => container.Resolve<A>(), () => container.Resolve<A>());
}
}

private static void ResolveObjectInstanceLoop()
{
var builder = new ContainerBuilder();
Expand Down

0 comments on commit cf3674a

Please sign in to comment.