Skip to content

Commit 9ed7d64

Browse files
author
Giorgio Tresoldi
committed
"BsonClassMap.RegisterClassMap" simultaneously causes exception
1 parent c4c1983 commit 9ed7d64

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

SharpRepository.MongoDbRepository/MongoDbRepositoryBase.cs

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ namespace SharpRepository.MongoDbRepository
2323
{
2424
private readonly string _databaseName;
2525
protected IMongoDatabase Database;
26+
static readonly object _lock = new object();
2627

2728
private readonly Dictionary<Type, BsonType> _keyTypeToBsonType =
2829
new Dictionary<Type, BsonType>
@@ -80,28 +81,32 @@ private void Initialize(IMongoDatabase mongoDatabase = null)
8081
{
8182
Database = mongoDatabase ?? new MongoClient("mongodb://localhost/default").GetDatabase(MongoUrl.Create("mongodb://localhost/default").DatabaseName);
8283

83-
if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
84-
{
85-
var primaryKeyPropInfo = GetPrimaryKeyPropertyInfo();
84+
if (BsonClassMap.IsClassMapRegistered(typeof(T)))
85+
return;
8686

87-
BsonClassMap.RegisterClassMap<T>(cm =>
88-
{
89-
cm.AutoMap();
90-
if (cm.IdMemberMap == null)
91-
{
92-
cm.SetIdMember(new BsonMemberMap(cm, primaryKeyPropInfo));
87+
lock (_lock)
88+
if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
89+
{
90+
var primaryKeyPropInfo = GetPrimaryKeyPropertyInfo();
9391

94-
if (_keyTypeToBsonType.ContainsKey(typeof(TKey)) && (_keyTypeToBsonGenerator.ContainsKey(typeof(TKey))))
92+
BsonClassMap.RegisterClassMap<T>(cm =>
93+
{
94+
cm.AutoMap();
95+
if (cm.IdMemberMap == null)
9596
{
96-
cm.IdMemberMap.SetSerializer(new StringSerializer(_keyTypeToBsonType[typeof(TKey)]));
97-
cm.IdMemberMap.SetIdGenerator(_keyTypeToBsonGenerator[typeof(TKey)]);
97+
cm.SetIdMember(new BsonMemberMap(cm, primaryKeyPropInfo));
98+
99+
if (_keyTypeToBsonType.ContainsKey(typeof(TKey)) && (_keyTypeToBsonGenerator.ContainsKey(typeof(TKey))))
100+
{
101+
cm.IdMemberMap.SetSerializer(new StringSerializer(_keyTypeToBsonType[typeof(TKey)]));
102+
cm.IdMemberMap.SetIdGenerator(_keyTypeToBsonGenerator[typeof(TKey)]);
103+
}
98104
}
99-
}
100105

101-
cm.Freeze();
102-
}
103-
);
104-
}
106+
cm.Freeze();
107+
}
108+
);
109+
}
105110
}
106111

107112
private IMongoCollection<T> BaseCollection()

0 commit comments

Comments
 (0)