Skip to content

Commit

Permalink
Making the cache dictionary thread safe
Browse files Browse the repository at this point in the history
Fixes moq#149
  • Loading branch information
Keboo committed Oct 3, 2022
1 parent 33fbf25 commit bbd7d79
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 20 deletions.
4 changes: 2 additions & 2 deletions Moq.AutoMock/AutoMocker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public AutoMocker(MockBehavior mockBehavior, DefaultValue defaultValue, DefaultV
};
}) ?? new Dictionary<Type, object?>();

private Dictionary<Type, IInstance>? TypeMap
private NonBlocking.ConcurrentDictionary<Type, IInstance>? TypeMap
=> Resolvers.OfType<CacheResolver>().FirstOrDefault()?.TypeMap;

private bool TryResolve(Type serviceType,
Expand Down Expand Up @@ -1054,7 +1054,7 @@ internal void CacheInstances(IEnumerable<(Type, IInstance)> instances)
});
}

private void WithTypeMap(Action<Dictionary<Type, IInstance>> onTypeMap)
private void WithTypeMap(Action<NonBlocking.ConcurrentDictionary<Type, IInstance>> onTypeMap)
{
if (TypeMap is { } typeMap)
{
Expand Down
1 change: 1 addition & 0 deletions Moq.AutoMock/Moq.AutoMock.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="NonBlocking" Version="2.1.0" />
<ProjectReference Include="../Generators/Generators.csproj">
<OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
Expand Down
36 changes: 18 additions & 18 deletions Moq.AutoMock/Resolvers/CacheResolver.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
namespace Moq.AutoMock.Resolvers;

/// <summary>
/// Provides the cache used by AutoMocker.
/// </summary>
public class CacheResolver : IMockResolver
{
internal Dictionary<Type, IInstance> TypeMap { get; } = new();

/// <inheritdoc />
public void Resolve(MockResolutionContext context)
{
if (TypeMap.TryGetValue(context.RequestType, out IInstance instance))
{
context.Value = instance;
}
}
}
namespace Moq.AutoMock.Resolvers;

/// <summary>
/// Provides the cache used by AutoMocker.
/// </summary>
public class CacheResolver : IMockResolver
{
internal NonBlocking.ConcurrentDictionary<Type, IInstance> TypeMap { get; } = new();

/// <inheritdoc />
public void Resolve(MockResolutionContext context)
{
if (TypeMap.TryGetValue(context.RequestType, out IInstance instance))
{
context.Value = instance;
}
}
}

0 comments on commit bbd7d79

Please sign in to comment.