I have created a simple .net core application connecting to mongoDb as described here https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-7.0&tabs=visual-studio
Database connection information is configured in appsettings.json file.
"DataSource": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "Root",
"CollectionName": "ApiLog"
},
I have a matching class
public class DatabaseSettings
{
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
public string CollectionName { get; set; } = null!;
}
I dont want to store db info in a file so how can I configure connection information in a production environment?
I expect something like
dotnet app.dll -DataSource.ConnectionString = mongodb://localhost:27017
in Program.cs i have;
builder.Services.Configure<DatabaseSettings>(
builder.Configuration.GetSection("DataSource"))
I want to access this configuration whenever i need it via dependency injection
public class LogService
{
private readonly IMongoCollection<ElekseLog> _collection;
public LogService(
IOptions<DatabaseSettings> databaseSettings)
{
var mongoClient = new MongoClient(
databaseSettings.Value.ConnectionString);
var mongoDatabase = mongoClient.GetDatabase(
databaseSettings.Value.DatabaseName);
_collection = mongoDatabase.GetCollection<ElekseLog>(
databaseSettings.Value.CollectionName);
}
}
But I couldn't make it work...