ticket-system/source/ticketAPI/data/MongoFactory.cs
2024-12-04 15:57:49 -05:00

45 lines
1.4 KiB
C#

using Microsoft.Extensions.Configuration;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
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)
{
//set up the use of guids globally for the mongo connection
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
_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);
}
}