Skip to content

Commit

Permalink
Update MongoClientHelpers.cs
Browse files Browse the repository at this point in the history
Cache MongoClient object so we don't thrash the constructor logic
  • Loading branch information
jas88 committed Oct 24, 2024
1 parent b0a57f3 commit 6726d4d
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/SmiServices/Common/MongoDB/MongoClientHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using NLog;
using SmiServices.Common.Options;
using System;
using System.Collections.Concurrent;
using System.Linq;

namespace SmiServices.Common.MongoDB
Expand All @@ -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();

/// <summary>
/// Creates a <see cref="MongoClient"/> from the given options, and checks that the user has the "readWrite" role for the given database
/// </summary>
Expand All @@ -24,8 +27,14 @@ public static class MongoClientHelpers
/// <param name="skipAuthentication"></param>
/// <param name="skipJournal"></param>
/// <returns></returns>
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}");

Expand Down

0 comments on commit 6726d4d

Please sign in to comment.