From 3af2457be0a94141c0d2133455a551e3c57f1982 Mon Sep 17 00:00:00 2001 From: "ba0007 (Bruno Arruda)" Date: Mon, 18 Jul 2022 14:48:55 +0200 Subject: [PATCH] feat: Add support to pass MongoClientSettings as a parameter of CreateClient --- .../DefaultMongoClientFactory.cs | 24 +++++++++++++------ .../IMongoClientFactory.cs | 5 ++-- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Arc4u.Standard.MongoDB/DefaultMongoClientFactory.cs b/src/Arc4u.Standard.MongoDB/DefaultMongoClientFactory.cs index 369e2861..58cc27a4 100644 --- a/src/Arc4u.Standard.MongoDB/DefaultMongoClientFactory.cs +++ b/src/Arc4u.Standard.MongoDB/DefaultMongoClientFactory.cs @@ -13,11 +13,11 @@ public DefaultMongoClientFactory(IOptionsMonitor clientSett _mongoContext = (TContext)serviceProvider.GetService(typeof(TContext)); } - IMongoDatabase _database; - IMongoClient _client; + private IMongoDatabase _database; + private IMongoClient _client; private static object _locker = new object(); - readonly IOptionsMonitor _clientSettings; - readonly TContext _mongoContext; + private readonly IOptionsMonitor _clientSettings; + private readonly TContext _mongoContext; public IMongoClient CreateClient() { @@ -35,13 +35,24 @@ public IMongoClient CreateClient() { _client = new MongoClient(settings); return _client; - } throw new NullReferenceException($"No mongo client settings defined for key {_mongoContext.DatabaseName}"); } + } + public IMongoClient CreateClient(MongoClientSettings mongoClientSettings) + { + if (null == mongoClientSettings) throw new NullReferenceException($"No mongo client settings defined for key {_mongoContext.DatabaseName}"); + lock (_locker) + { + if (null != _client) + return _client; + + _client = new MongoClient(mongoClientSettings); + return _client; + } } private IMongoDatabase GetDatabase() @@ -82,7 +93,6 @@ public IMongoCollection GetCollection() var db = GetDatabase(); return db.GetCollection(collectionNames[0]); - } } -} +} \ No newline at end of file diff --git a/src/Arc4u.Standard.MongoDB/IMongoClientFactory.cs b/src/Arc4u.Standard.MongoDB/IMongoClientFactory.cs index edaef2d8..a2d556dd 100644 --- a/src/Arc4u.Standard.MongoDB/IMongoClientFactory.cs +++ b/src/Arc4u.Standard.MongoDB/IMongoClientFactory.cs @@ -9,9 +9,10 @@ public interface IMongoClientFactory where TContext : DbContext { IMongoClient CreateClient(); + IMongoClient CreateClient(MongoClientSettings mongoClientSettings); + IMongoCollection GetCollection(string collectionName); IMongoCollection GetCollection(); } - -} +} \ No newline at end of file