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; /// /// Sets up the configuration, must be called before using GetDatabase() /// /// 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; } /// /// 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); } }