public void AddClient(string key, MongoCredential credential, MongoServerAddress address) { if (address == null) { throw new ArgumentNullException(nameof(address)); } MongoClientSettings settings = new MongoClientSettings() { Server = address }; if (credential != null) { settings.Credential = credential; } var client = new MongoClient(settings); if (!MongoClients.Keys.Contains(key)) { MongoClients.Add(key, client); } else { MongoClients[key] = client; } }
private MongoClient GetClient(string connectionString) { MongoClient client = null; _clientLocker.EnterReadLock(); try { if (MongoClients.ContainsKey(connectionString)) { client = MongoClients[connectionString]; } else { _clientLocker.ExitReadLock(); _clientLocker.EnterWriteLock(); try { if (!MongoClients.ContainsKey(connectionString)) { client = new MongoClient(connectionString); MongoClients.Add(connectionString, client); } client = MongoClients[connectionString]; } finally { _clientLocker.ExitWriteLock(); } } } finally { if (_clientLocker.IsReadLockHeld) { _clientLocker.ExitReadLock(); } } return(client); }