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

前端 未结 3 1845
一个人的身影
一个人的身影 2021-01-24 00:13

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

相关标签:
3条回答
  • 2021-01-24 00:36

    No. There is no support for this. Two things, though:

    1. While the data being provided in each case is the same, the two things are not the same. It's not a duplication when both just happen to be using the same data source, as that may just as well not be the case.

    2. There's nothing magical about the ConnectionStrings section, except that it allows you to use the GetConnectionString sugar. You could just as well do something like:

      services.AddDbContext(o =>
          o.UseSqlServer(Configuration["Nlog:targets:database:connectionString"]));
      

      Whether or not that's appropriate is a separate discussion. The point is that you don't have to have the value multiple times, if you're just dead set against it.

    0 讨论(0)
  • 2021-01-24 00:37

    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();
    
    0 讨论(0)
  • 2021-01-24 00:44

    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

    0 讨论(0)
提交回复
热议问题