using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using MongoDB.Driver; namespace StellaOps.Graph.Indexer.Infrastructure; public static class MongoServiceCollectionExtensions { public static IServiceCollection AddGraphMongoDatabase( this IServiceCollection services, Action configure) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(configure); services.Configure(configure); services.AddSingleton(sp => { var opts = sp.GetRequiredService>().Value; Validate(opts); return new MongoClient(opts.ConnectionString); }); services.AddSingleton(sp => { var opts = sp.GetRequiredService>().Value; Validate(opts); return sp.GetRequiredService().GetDatabase(opts.DatabaseName); }); return services; } private static void Validate(MongoDatabaseOptions options) { if (string.IsNullOrWhiteSpace(options.ConnectionString)) { throw new InvalidOperationException("Mongo connection string must be provided."); } if (string.IsNullOrWhiteSpace(options.DatabaseName)) { throw new InvalidOperationException("Mongo database name must be provided."); } } }