@@ -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