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);