Connecting to Mongo Database C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | using MongoDB.Bson; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; public class MongoConnectionManager : IMongoConnectionManager { public IMongoClient client { get; set;} private readonly MongoDBConfigSettings _mongoDBSettings; //Setup Mongo Client in the connection Manager constructor when the instance is created, so that it can be dependency injected into other classes public MongoConnectionManager(IOptions<MongoDBConfigSettings> mongoDBSettings) { mongoDBSettings = _mongoDBSettings.Value; client = GetMongoClient(); } } |
GetMongoClient -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | private IMongoClient GetMongoClient() { try { var settings = new MongoClientSettings { ConnectionMode = ConnectionMode.Automatic, UseSSL = MongoDBSettings.UseSSL, //Get all the settings from Config (Can be in Spring Cloud or some project config files) MinConnectionPoolSize = MongoDBSettings.MinConnectionPoolSize, MaxConnectionIdleTime = new TimeSpan(0,0,0,0,MongoDBSettings.MaxConnectionIdleTime), ServerSelectionTimeout = new TimeSpan(0,0,0,0,MongoDBSettings.ServerSelectionTimeout), ConnectTimeout = new TimeSpan(0,0,0,0,MongoDBSettings.ConnectTimeout), SocketTimeout = new TimeSpan(0,0,0,0,MongoDBSettings.SocketTimeout) }; var pack = new ConventionPack { new IgnoreExtraElementsConvention(true) }; ConventionRegistry.Register("IgnoreConvention", pack, t => true); //Set up Read/Write Preferences var wc = new WriteConcern(WriteConcern.WMajority.W, new TimeSpan(0,0,0,0,MongoDBSettings.WriteTimeout)); settings.WriteConcern = wc; settings.ReadPreference = ReadPreference.PrimaryPreferred; //Configuring the Mongo Server to connect var serverslist = MongoDBSettings.Servers; var servers = serverslist.Split(','); var mdbServerList = servers.Select(server=>server.Split(',').Select(addressportArray=> new MongoServerAddress(addressportArray[0], Convert.ToInt32(addressportArray[1])))).ToList(); settings.Servers = mdbServerList; settings.Credential = MongoCredential.CreatePlainCredential("$external", MongoDBSettings.User, MongoDBSettings.Password); settings.RetryWrites = true; var connectionString = MongoDBSettings.MongoConnectionStringOverride; return !string.IsNullOrWhiteSpace(connectionString) ? new MongoClient(connectionString) : new MongoClient(settings); } catch (System.Exception ex) { throw ex; } } |
GetDatabase -
1 2 3 4 5 | private IMongoDatabase GetDatabase() { if (client == null) { throw ex; }; return client.GetDatabase(databaseName); } |
GetCollection -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | public IMongoCollection<T> GetCollection<T>(string collectionName) { IMongoDatabase db = GetDatabase(); IMongoCollection<T> collection = null; if(GetMongoDBConnectionStatus()) { collection = db.GetCollection<T>(collectionName) }; else { RetryMongoHasCollection() }; return collection; } //Ping the database to check db connection public bool GetMongoDBConnectionStatus() { IMongoDatabase db = null; try { db = GetDatabase(); var pingCommand = new BsonDocument("ping", 1;); var status = db.RunCommand<MongoPingStatus>(pingCommand); return status.ok == 1; } } //Attempt to retry connection public bool RetryMongoHasCollection() { var maxRetryCount = MongoDBSettings.maxRetryCount; var retryInterval = MongoDBSettings.retryInterval; var connected = false; int i=1; for (int i = 1; i < maxRetryCount; i++) { System.Threading.Thread.Sleep(retryInterval); if(GetMongoDBConnectionStatus()) { connected = true; break; } } if (connected) { Log("Connected after x attempts")} else { throw ex)"Failed to Reconnect"}; return true; } |
Comments
Post a Comment