I'm brand new to NoSQL and I have a question. I've created a DatabaseHandler that allows me to grab a collection globally across my solution. I then noticed that I'm using 1 instance of IMongoDatabase for the entire lifetime of my application, is this correct?
Obviously coming form a MySQL background I'm used to using and opening a new connection on each call to DatabaseHandler
I'm just asking for someone to check if this is okay, as I'm really new and It's sort of confusing me.
internal sealed class DatabaseHandler : IDisposable
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
public IMongoDatabase MongoDatabase;
public DatabaseHandler()
{
var config = Program.Server.ConfigHandler;
var databaseHost = config.GetValue("database.hostname");
var databasePort = config.GetValue("database.port");
var mongoClient = new MongoClient(new MongoClientSettings
{
Server = new MongoServerAddress(databaseHost, databasePort.ToInteger()),
ServerSelectionTimeout = TimeSpan.FromSeconds(3)
});
MongoDatabase = mongoClient.GetDatabase(config.GetValue("database.name"));
var isMongoLive = MongoDatabase.RunCommandAsync((Command<BsonDocument>)"{ping:1}").Wait(1000);
if (!isMongoLive)
{
Logger.Error("We couldn't establish a connection with the database.");
}
}
public IMongoCollection<T> GetCollection<T>(string name)
{
return MongoDatabase.GetCollection<T>(name);
}
public void Dispose()
{
MongoDatabase.D
}
}