Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference another value within the same appsettings.json file?

I need database connection string in two places in appsettings.json.

Is it possible to introduce common variable or json-path related references into json file to avoid potencial problems?

It would be lovely to have it without touching c# code.

{
...
  "ConnectionStrings": {
    "Default": "Host=localhost;Database=db;Port=5432;Username=postgres;Password=postgres"
  },
  "Nlog": {
    "targets": {
      "database": {
        "type": "Database",
        "dbProvider": "Npgsql.NpgsqlConnection, Npgsql",
        "connectionString": "Host=localhost;Database=db;Port=5432;Username=postgres;Password=postgres",
...
      }
    }
...
}
like image 532
GetoX Avatar asked Jun 20 '26 05:06

GetoX


2 Answers

NLog has the ability to lookup values in the appsettings.json. You can do it like this with ${configsetting}:

{
...
  "ConnectionStrings": {
    "Default": "Host=localhost;Database=db;Port=5432;Username=postgres;Password=postgres"
  },
  "Nlog": {
    "targets": {
      "database": {
        "type": "Database",
        "dbProvider": "Npgsql.NpgsqlConnection, Npgsql",
        "connectionString": "${configsetting:item=ConnectionStrings.Default}",
...
      }
    }
...
}

See also https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

like image 79
Rolf Kristensen Avatar answered Jun 21 '26 22:06

Rolf Kristensen


I've created a nuget package exactly for this! Check it out here: https://www.nuget.org/packages/TemplateFormattedConfiguration/

In your example you should do this:

{
...
    "ConnectionStrings": {
"Default": "Host=localhost;Database=db;Port=5432;Username=postgres;Password=postgres"
  },
  "Nlog": {
    "targets": {
      "database": {
        "type": "Database",
        "dbProvider": "Npgsql.NpgsqlConnection, Npgsql",
        "connectionString": "{ConnectionStrings:Default}",
...
      }
    }
...
}

And in your Startup.cs (or Program.cs) you'll add this:

        configuration.EnableTemplatedConfiguration();
like image 20
Javi Avatar answered Jun 21 '26 22:06

Javi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!