locked
Best practice when connect to a mongodb RRS feed

  • Question

  • User-1000104858 posted

    Hi!

    We have created a mongodb on a VM in Azure. Now we are confusing if we should add some retry logic to the connection to mongodb or if the MongoClient is handling connection problem? (We are only using one db)

    This is what we have:

    namespace cMain.Mongo
    {
        internal class Connection
        {
            private static IMongoClient _client;
            private static IMongoDatabase _db;
    
            internal static IMongoClient Client
            {
                get
                {
                    if (_client != null)
                    {
                        return _client;
                    }
                    _client = ConnectClient();
                    return _client;
                }
            }
    
            internal static IMongoDatabase Database
            {
                get
                {
                    if (_db != null)
                    {
                        return _db;
                    }
                    _db = ConnectDatabase();
                    return _db;
                }
            }
    
            private static IMongoClient ConnectClient()
            {
                return new MongoClient(System.Configuration.ConfigurationManager.ConnectionStrings["MongoDb"].ConnectionString);
            }
    
            private static IMongoDatabase ConnectDatabase()
            {
                return RetryHelper.Retry(() => Client.GetDatabase(Properties.Settings.Default.MongoDbName));
            }
        }
    }

    RetryHelper is a simple class that run the function max 5 times if there is an exception. Should we have retry on GetDatabase?

    Then we have this:

    var Coll = Connection.Database.GetCollection<ErrorLog>("Errors");
    Coll.Indexes.CreateOne(new BsonDocument("LogId", 1), new CreateIndexOptions { Unique = true });
    Coll.InsertOne(errorObject);
    

    Should we add retry on GetCollection and/or InsertOne?


    Thanx for the help!

    Tuesday, February 7, 2017 10:23 PM

Answers

  • User765422875 posted

    I've been on projects where implementing retry logic was a requirement and others where it was not. People will have varying opinions on what is best practice for retry logic.

    At a minimum, I think you should read the following on MSDN which goes over how to implement this pattern as well as suitable uses cases for it.

    https://msdn.microsoft.com/en-us/library/dn589788.aspx

    Even better is to use a framework such as Polly.

    https://github.com/App-vNext/Polly

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 17, 2017 6:43 PM