Home > Net >  .NET Core pass configuration section via command line
.NET Core pass configuration section via command line

Time:01-20

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?

CodePudding user response:

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.

  • Related