Geshem W
Geshem W

Reputation: 137

Using multiple connection strings for the same DBContext

I am working on a asp.net core project which uses MongoDB and I am using dependency injection as well.

How current system works

There is only one database and the connection string is saved in the appsettings.json. Some devices will be constantly sending data through the API to save it in the MongoDB database which works as it should :)

Now I have to enhance it, there will be multiple databases and data should be saved in the relevant database based on the API request (i will be getting the database name in the API request).

My question is how that can I change the database based on the API request? while using the same DbContext. It is not an option to create multiple DbContext.

I am somewhat new to MongoDb and asp.net core so any help or guidance is much appreciated.

This is my DbContext class

public class DbContext
{
    private IMongoDatabase _database;
    protected readonly MongoClient mongoClient;

    public DbContext(MongoSetting dbConnSettings)
    {
        var mongoUrl = new MongoUrl(dbConnSettings.ConnectionString);
        var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);

        mongoClient  = new MongoClient(mongoClientSettings);
        if (mongoClient != null)
            _database = mongoClient.GetDatabase(dbConnSettings.database);
    }...

Section of my StartUp class

services.AddTransient<CareHomeContext>();

services.AddSingleton(provider => provider.GetService<IOptions<MongoSetting>>().Value);

Upvotes: 0

Views: 2512

Answers (1)

Sivaram Koduri
Sivaram Koduri

Reputation: 519

If I understand your usecase correctly, it might be needed to use different databases in each request as well.

Hence I suggest to make database name as an optional parameter (so that you can use a default value from the configuration in case the database name is not provided in the request) to the DbContext class methods and create a method to get the database object (instead of getting it in the constructor) in the DbContext class as below.

private IMongoDatabase GetDatabase(string databaseName) => mongoClient.GetDatabase(databaseName ?? defaultDatabaseName);

Invoke the above method in each DbContext class method. e.g.

public async Task InsertAsync(string collectionName, Dictionary<string, object> fields, string databaseName = null) {
   var database = GetDatabase(databaseName);
   // Insert Code here
}

I hope this would help.

Upvotes: 1

Related Questions