40 lines
1.2 KiB
C#
40 lines
1.2 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using MongoDB.Driver;
|
|
|
|
namespace data;
|
|
|
|
public static class MongoFactory
|
|
{
|
|
private static IConfiguration? _config;
|
|
|
|
/// <summary>
|
|
/// Sets up the configuration, must be called before using GetDatabase()
|
|
/// </summary>
|
|
/// <param name="config"></param>
|
|
public static void InitConfig(IConfiguration config)
|
|
{
|
|
_config = config;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets up the connection to Mongo and returns the database from Configuration
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
/// <exception cref="NullReferenceException"></exception>
|
|
/// <exception cref="Exception"></exception>
|
|
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);
|
|
}
|
|
} |