5

In appsettingsjson file i have:

  "DataSource": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "Root",
    "CollectionName": "ApiLog"
  },

in Program.cs, i get this data like this

builder.Services.Configure<DatabaseSettings>(
    builder.Configuration.GetSection("DataSource"));

where DatabaseSettings class is;

    public class DatabaseSettings
    {
        public string ConnectionString { get; set; } = null!;

        public string DatabaseName { get; set; } = null!;

        public string CollectionName { get; set; } = null!;
    }

Then i can access instance of DatabaseSettings via dependency injection like:

    public class LogService
    {
        private readonly IMongoCollection<Log> _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);
        }
    }

the question is i dont want to store db info in appsettings json file. I want to pass tis info from command line without changing the code. How can I achieve this?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
yılmaz
  • 365
  • 1
  • 14

1 Answers1

4

You need to "flatten" the parameters by joining "path elements" with : and pass as key-value pairs. For example:

yourapp "DataSource:ConnectionString"="mongodb://localhost:27017"

Or

yourapp  --DataSource:ConnectionString=mongodb://localhost:27017

Some info can be found in the docs - Command-line configuration provider.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thanks! How can I pass this configuration from IIS? – yılmaz Jan 19 '23 at 14:57
  • 1
    @yılmaz sorry, a bit late but maybe useful - you might need to check out the IIS enviroinment variables and set data by using them, note that `:` should be replaced with two `_` in the variable name, i.e. - `DataSource:ConnectionString` -> `DataSource__ConnectionString` – Guru Stron Apr 09 '23 at 20:39