'Adding Multiple MongoDb Collections in app.seeting file and how can they be called and used from service class
I having multiple collections such as one for users, courses, action plans and diseases how can i add them in appsettings.json and how to call them separately in service class when utilizing them
appsetting.json file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"DatabaseSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "local",
"CollectionName": "startup_log"
}
}
Start Up File
services.AddScoped<DataInterface, DataService>();
services.Configure<AppDbConfig>(Configuration.GetSection("DatabaseSettings"));
AppDbConfig Class
public class AppDbConfig
{
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
public string CollectionName { get; set; } = null!;
}
DataService Class
private readonly IMongoCollection<startup_log> startupLogs;
public DataService(IOptions<AppDbConfig> settings)
{
MongoClient client = new MongoClient(settings.Value.ConnectionString);
IMongoDatabase database = client.GetDatabase(settings.Value.DatabaseName);
startupLogs = database.GetCollection< startup_log >(settings.Value.CollectionName);
}
Start Up Log File
public class startup_log
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("hostname")]
public string HostName { get; set; } = null!;
[BsonElement("startTime")]
public DateTime StartTime { get; set; }
[BsonElement("startTimeLocal")]
public string StartTimeLocal { get; set; } = null!;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
