|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using Aspire.MongoDB.Driver; |
| 5 | +using Microsoft.Extensions.Configuration; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using MongoDB.Driver; |
| 8 | + |
| 9 | +namespace Microsoft.Extensions.Hosting; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Extension methods for connecting MongoDB database with MongoDB.Driver client. |
| 13 | +/// </summary> |
| 14 | +public static class AspireMongoDbDriverExtensions |
| 15 | +{ |
| 16 | + private const string DefaultConfigSectionName = "Aspire:MongoDB"; |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Registers <see cref="IMongoClient"/> and <see cref="IMongoDatabase"/> instances for connecting MongoDB database with MongoDB.Driver client. |
| 20 | + /// </summary> |
| 21 | + /// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param> |
| 22 | + /// <param name="connectionName">A name used to retrieve the connection string from the ConnectionStrings configuration section.</param> |
| 23 | + /// <param name="configureSettings">An optional delegate that can be used for customizing options. It's invoked after the settings are read from the configuration.</param> |
| 24 | + /// <remarks>Reads the configuration from "Aspire:MongoDB" section.</remarks> |
| 25 | + /// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="MongoDbSettings.ConnectionString"/> is not provided.</exception> |
| 26 | + public static void AddMongoDbDataSource( |
| 27 | + this IHostApplicationBuilder builder, |
| 28 | + string connectionName, |
| 29 | + Action<MongoDbSettings>? configureSettings = null) |
| 30 | + => AddMongoDbDataSource(builder, DefaultConfigSectionName, configureSettings, connectionName, serviceKey: null); |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Registers <see cref="IMongoClient"/> and <see cref="IMongoDatabase"/> instances for connecting MongoDB database with MongoDB.Driver client. |
| 34 | + /// </summary> |
| 35 | + /// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param> |
| 36 | + /// <param name="name">The name of the component, which is used as the <see cref="ServiceDescriptor.ServiceKey"/> of the service and also to retrieve the connection string from the ConnectionStrings configuration section.</param> |
| 37 | + /// <param name="configureSettings">An optional delegate that can be used for customizing options. It's invoked after the settings are read from the configuration.</param> |
| 38 | + /// <remarks>Reads the configuration from "Aspire:MongoDB:{name}" section.</remarks> |
| 39 | + /// <exception cref="ArgumentNullException">Thrown if mandatory <paramref name="builder"/> is null.</exception> |
| 40 | + /// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="MongoDbSettings.ConnectionString"/> is not provided.</exception> |
| 41 | + public static void AddKeyedMongoDbDataSource( |
| 42 | + this IHostApplicationBuilder builder, |
| 43 | + string name, |
| 44 | + Action<MongoDbSettings>? configureSettings = null) |
| 45 | + { |
| 46 | + ArgumentException.ThrowIfNullOrEmpty(name); |
| 47 | + |
| 48 | + AddMongoDbDataSource(builder, $"{DefaultConfigSectionName}:{name}", configureSettings, connectionName: name, serviceKey: name); |
| 49 | + } |
| 50 | + |
| 51 | + private static void AddMongoDbDataSource( |
| 52 | + IHostApplicationBuilder builder, |
| 53 | + string configurationSectionName, |
| 54 | + Action<MongoDbSettings>? configureSettings, |
| 55 | + string connectionName, |
| 56 | + string? serviceKey) |
| 57 | + { |
| 58 | + ArgumentNullException.ThrowIfNull(builder); |
| 59 | + |
| 60 | + var settings = builder.GetMongoDbSettings( |
| 61 | + connectionName, |
| 62 | + configurationSectionName, |
| 63 | + configureSettings); |
| 64 | + |
| 65 | + settings.ValidateSettings(connectionName, configurationSectionName); |
| 66 | + |
| 67 | + builder.RegisterMongoDbServices(settings, serviceKey); |
| 68 | + } |
| 69 | + |
| 70 | + private static void RegisterMongoDbServices(this IHostApplicationBuilder builder, MongoDbSettings settings, string? serviceKey) |
| 71 | + { |
| 72 | + var mongoUrl = MongoUrl.Create(settings.ConnectionString); |
| 73 | + |
| 74 | + builder.Services.AddMongoClient(mongoUrl, serviceKey); |
| 75 | + |
| 76 | + if (!string.IsNullOrWhiteSpace(mongoUrl.DatabaseName)) |
| 77 | + { |
| 78 | + builder.Services.AddMongoDatabase(mongoUrl, serviceKey); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private static IServiceCollection AddMongoClient(this IServiceCollection services, MongoUrl mongoUrl, string? serviceKey = null) |
| 83 | + { |
| 84 | + if (string.IsNullOrWhiteSpace(serviceKey)) |
| 85 | + { |
| 86 | + return services.AddSingleton<IMongoClient>(_ => new MongoClient(mongoUrl)); |
| 87 | + } |
| 88 | + |
| 89 | + return services |
| 90 | + .AddKeyedSingleton<IMongoClient>(serviceKey, (_, __) => new MongoClient(mongoUrl)); |
| 91 | + } |
| 92 | + |
| 93 | + private static IServiceCollection AddMongoDatabase(this IServiceCollection services, MongoUrl mongoUrl, string? serviceKey = null) |
| 94 | + { |
| 95 | + if (string.IsNullOrWhiteSpace(serviceKey)) |
| 96 | + { |
| 97 | + return services.AddSingleton<IMongoDatabase>(provider => |
| 98 | + { |
| 99 | + return provider |
| 100 | + .GetRequiredService<IMongoClient>() |
| 101 | + .GetDatabase(mongoUrl.DatabaseName); |
| 102 | + }); |
| 103 | + } |
| 104 | + |
| 105 | + return services.AddKeyedSingleton<IMongoDatabase>(serviceKey, (provider, _) => |
| 106 | + { |
| 107 | + return provider |
| 108 | + .GetRequiredKeyedService<IMongoClient>(serviceKey) |
| 109 | + .GetDatabase(mongoUrl.DatabaseName); |
| 110 | + }); |
| 111 | + } |
| 112 | + |
| 113 | + private static MongoDbSettings GetMongoDbSettings( |
| 114 | + this IHostApplicationBuilder builder, |
| 115 | + string connectionName, |
| 116 | + string configurationSectionName, |
| 117 | + Action<MongoDbSettings>? configureSettings) |
| 118 | + { |
| 119 | + MongoDbSettings settings = new(); |
| 120 | + |
| 121 | + builder.Configuration |
| 122 | + .GetSection(configurationSectionName) |
| 123 | + .Bind(settings); |
| 124 | + |
| 125 | + if (builder.Configuration.GetConnectionString(connectionName) is string connectionString) |
| 126 | + { |
| 127 | + settings.ConnectionString = connectionString; |
| 128 | + } |
| 129 | + |
| 130 | + configureSettings?.Invoke(settings); |
| 131 | + |
| 132 | + return settings; |
| 133 | + } |
| 134 | + |
| 135 | + private static void ValidateSettings(this MongoDbSettings settings, string connectionName, string configurationSectionName) |
| 136 | + { |
| 137 | + if (string.IsNullOrEmpty(settings.ConnectionString)) |
| 138 | + { |
| 139 | + throw new InvalidOperationException($"ConnectionString is missing. It should be provided in 'ConnectionStrings:{connectionName}' or under the 'ConnectionString' key in '{configurationSectionName}' configuration section."); |
| 140 | + } |
| 141 | + } |
| 142 | +} |
0 commit comments