diff --git a/src/SmiServices/Common/MongoDB/MongoClientHelpers.cs b/src/SmiServices/Common/MongoDB/MongoClientHelpers.cs index 557af5d54..fa79a29ec 100644 --- a/src/SmiServices/Common/MongoDB/MongoClientHelpers.cs +++ b/src/SmiServices/Common/MongoDB/MongoClientHelpers.cs @@ -4,6 +4,7 @@ using NLog; using SmiServices.Common.Options; using System; +using System.Collections.Concurrent; using System.Linq; namespace SmiServices.Common.MongoDB @@ -16,6 +17,8 @@ public static class MongoClientHelpers private static readonly ListCollectionNamesOptions _listOptions = new(); + private static readonly ConcurrentDictionary<(MongoDbOptions, string, bool, bool), MongoClient> _clientCache = new(); + /// /// Creates a from the given options, and checks that the user has the "readWrite" role for the given database /// @@ -24,8 +27,14 @@ public static class MongoClientHelpers /// /// /// - public static MongoClient GetMongoClient(MongoDbOptions options, string applicationName, bool skipAuthentication = false, bool skipJournal = false) + public static MongoClient GetMongoClient(MongoDbOptions options, string applicationName, + bool skipAuthentication = false, bool skipJournal = false) => + _clientCache.GetOrAdd((options, applicationName, skipAuthentication, skipJournal), + CreateMongoClient); + private static MongoClient CreateMongoClient((MongoDbOptions, string, bool, bool) valueTuple) { + var (options, applicationName, skipAuthentication, skipJournal) = valueTuple; + if (!options.AreValid(skipAuthentication)) throw new ApplicationException($"Invalid MongoDB options: {options}");