using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
namespace data;
public static class MongoFactory
{
private static IConfiguration? _config;
///
/// Sets up the configuration, must be called before using GetDatabase()
///
///
public static void InitConfig(IConfiguration config)
{
_config = config;
}
///
/// Sets up the connection to Mongo and returns the database from Configuration
///
///
///
///
public static IMongoDatabase GetDatabase()
{
if (_config == null)
{
throw new NullReferenceException("Configuration is not set");
}
if (String.IsNullOrEmpty(_config.GetSection("Mongo:ConnectionString").Value))
{
throw new Exception("No MongoDB connection string");
}
var client = new MongoClient(_config.GetSection("Mongo:ConnectionString").Value);
return client.GetDatabase(_config.GetSection("Mongo:Database").Value);
}
}