From c12214d02933161a9ef782441fd8d191666d144b Mon Sep 17 00:00:00 2001 From: Roland Schmitt <13732585+agentschmitt@users.noreply.github.com> Date: Wed, 3 Dec 2025 18:11:06 +0100 Subject: [PATCH] MET-4505 change constructor logic to lazy otherwise injection of any repository will crash when mongodb is not configured instead if should only run on error on first method call on the Collection --- src/Samhammer.Mongo/BaseRepositoryMongo.cs | 17 +++++++++++------ src/Samhammer.MongoDb.sln.DotSettings | 2 ++ 2 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 src/Samhammer.MongoDb.sln.DotSettings diff --git a/src/Samhammer.Mongo/BaseRepositoryMongo.cs b/src/Samhammer.Mongo/BaseRepositoryMongo.cs index cb284ed..49ea919 100644 --- a/src/Samhammer.Mongo/BaseRepositoryMongo.cs +++ b/src/Samhammer.Mongo/BaseRepositoryMongo.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using MongoDB.Driver; @@ -12,19 +13,23 @@ public class BaseRepositoryMongo : IBaseRepositoryMongo { protected ILogger> Logger { get; } - protected IMongoCollection Collection { get; } + protected IMongoCollection Collection => collection.Value; - private IMongoDatabase Database { get; } + private IMongoDatabase Database => database.Value; protected FilterDefinitionBuilder Filter => Builders.Filter; protected UpdateDefinitionBuilder Update => Builders.Update; - + + private readonly Lazy> collection; + + private readonly Lazy database; + public BaseRepositoryMongo(ILogger> logger, IMongoDbConnector connector, string databaseName = null) { Logger = logger; - Database = connector.GetMongoDatabase(databaseName); - Collection = GetCollection(); + database = new Lazy(() => connector.GetMongoDatabase(databaseName)); + collection = new Lazy>(GetCollection); } protected IMongoCollection GetCollection() diff --git a/src/Samhammer.MongoDb.sln.DotSettings b/src/Samhammer.MongoDb.sln.DotSettings new file mode 100644 index 0000000..9a953fd --- /dev/null +++ b/src/Samhammer.MongoDb.sln.DotSettings @@ -0,0 +1,2 @@ + + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="True" Prefix="" Suffix="" Style="aaBb" /></Policy> \ No newline at end of file