Skip to content

Commit

Permalink
Register MongoDb client as singleton (#6013)
Browse files Browse the repository at this point in the history
Co-authored-by: Sipke Schoorstra <[email protected]>
  • Loading branch information
rosca-sabina and sfmskywalker authored Oct 12, 2024
1 parent 1b4ce45 commit 090a3fd
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/modules/Elsa.MongoDb/Features/MongoDbFeature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ public override void Apply()
{
Services.Configure(Options);

Services.AddScoped(sp => CreateDatabase(sp, ConnectionString));
var mongoUrl = new MongoUrl(ConnectionString);
Services.AddSingleton(sp => CreateMongoClient(sp, mongoUrl));
Services.AddScoped(sp => CreateDatabase(sp, mongoUrl));

Services.TryAddScoped<DefaultNamingStrategy>();
Services.AddScoped(CollectionNamingStrategy);
Expand Down Expand Up @@ -95,11 +97,10 @@ private static void TryRegisterSerializerOrSkipWhenExist(Type type, IBsonSeriali
}
}

private static IMongoDatabase CreateDatabase(IServiceProvider sp, string connectionString)
private static IMongoClient CreateMongoClient(IServiceProvider sp, MongoUrl mongoUrl)
{
var options = sp.GetRequiredService<IOptions<MongoDbOptions>>().Value;

var mongoUrl = new MongoUrl(connectionString);
var settings = MongoClientSettings.FromUrl(mongoUrl);

settings.ClusterConfigurator = cb => cb.Subscribe(new DiagnosticsActivityEventSubscriber());
Expand All @@ -111,8 +112,13 @@ private static IMongoDatabase CreateDatabase(IServiceProvider sp, string connect
settings.RetryWrites = options.RetryWrites;
settings.SslSettings = options.SslSettings;

var mongoClient = new MongoClient(settings);
return mongoClient.GetDatabase(mongoUrl.DatabaseName);
return new MongoClient(settings);
}

private static IMongoDatabase CreateDatabase(IServiceProvider sp, MongoUrl mongoUrl)
{
var client = sp.GetRequiredService<IMongoClient>();
return client.GetDatabase(mongoUrl.DatabaseName);
}

private static string GetApplicationName(MongoClientSettings settings) =>
Expand Down

0 comments on commit 090a3fd

Please sign in to comment.