Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f662081

Browse files
committed
Protect AutoMappingStore from Threading issues.
1 parent 20fa57e commit f662081

File tree

1 file changed

+33
-12
lines changed

1 file changed

+33
-12
lines changed

source/MongoDB/Configuration/Mapping/AutoMappingStore.cs

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Threading;
34
using MongoDB.Configuration.Mapping.Auto;
45
using MongoDB.Configuration.Mapping.Model;
56

@@ -11,6 +12,7 @@ public class AutoMappingStore : IMappingStore
1112
{
1213
private readonly IAutoMapper _autoMapper;
1314
private readonly Dictionary<Type, IClassMap> _autoMaps;
15+
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
1416
private readonly IMappingStore _wrappedMappingStore;
1517

1618
/// <summary>
@@ -71,23 +73,42 @@ public AutoMappingStore(IAutoMapper autoMapper, IMappingStore mappingStore)
7173
/// <returns></returns>
7274
public IClassMap GetClassMap(Type classType)
7375
{
74-
IClassMap classMap;
75-
76-
if(_autoMaps.TryGetValue(classType, out classMap))
77-
return classMap;
78-
79-
if(_wrappedMappingStore != null)
76+
try
8077
{
81-
classMap = _wrappedMappingStore.GetClassMap(classType);
82-
if(classMap != null)
78+
_lock.EnterUpgradeableReadLock();
79+
80+
IClassMap classMap;
81+
if(_autoMaps.TryGetValue(classType, out classMap))
8382
return classMap;
84-
}
8583

86-
classMap = _autoMapper.CreateClassMap(classType, GetClassMap);
84+
if(_wrappedMappingStore != null)
85+
{
86+
classMap = _wrappedMappingStore.GetClassMap(classType);
87+
if(classMap != null)
88+
return classMap;
89+
}
90+
91+
classMap = _autoMapper.CreateClassMap(classType, GetClassMap);
8792

88-
_autoMaps.Add(classType, classMap);
93+
try
94+
{
95+
_lock.EnterWriteLock();
8996

90-
return classMap;
97+
_autoMaps.Add(classType, classMap);
98+
99+
return classMap;
100+
}
101+
finally
102+
{
103+
if(_lock.IsWriteLockHeld)
104+
_lock.ExitWriteLock();
105+
}
106+
}
107+
finally
108+
{
109+
if(_lock.IsUpgradeableReadLockHeld)
110+
_lock.ExitUpgradeableReadLock();
111+
}
91112
}
92113
}
93114
}

0 commit comments

Comments
 (0)