最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Set Const or static readonly field value from appsettings.json through dependency injection in .net core 9 - Stack Overflow

programmeradmin4浏览0评论

I have this MagicSgtrings class that holds some constants which I'm using in my worker service.

internal class MagicStrings
{
    public const string HttpClientName = "X_HttpClient";
  ...
}

usage: MagicStrings.HttpClientName

I also have those values set in appsettings.json, MagicStrings being used like fallback for configuration settings:

public Worker( IConfiguration config) => (_config) = (config){
...
   protected override async Task ExecuteAsync(CancellationToken stoppingToken)
   {
    ...
    var httpClient = _httpClientFactory.CreateClient(
        _config.GetValue<string>("HttpClientBasicConfig:HttpClientName")
        ?? MagicStrings.HttpClientName);
   }
}

What I would like is to have this _config.GetValue<string>("HttpClientBasicConfig:HttpClientName") ?? MagicStrings.HttpClientName) moved into MagicStrings class something like this:

internal class MagicStrings
{
    private readonly IConfiguration _config = null!;

    public MagicStrings(IConfiguration config) => (_config) = (config);

    public const string HttpClientName =
        _config.GetValue<string>("HttpClientBasicConfig:HttpClientName")
        ?? "X_HttpClient";
  or
    public static readonly string HttpClientName2 =
        _config.GetValue<string>("HttpClientBasicConfig:HttpClientName")
        ?? "X_HttpClient";
...

So I can used it like MagicStrings.HttpClientName in the entire app

I have this MagicSgtrings class that holds some constants which I'm using in my worker service.

internal class MagicStrings
{
    public const string HttpClientName = "X_HttpClient";
  ...
}

usage: MagicStrings.HttpClientName

I also have those values set in appsettings.json, MagicStrings being used like fallback for configuration settings:

public Worker( IConfiguration config) => (_config) = (config){
...
   protected override async Task ExecuteAsync(CancellationToken stoppingToken)
   {
    ...
    var httpClient = _httpClientFactory.CreateClient(
        _config.GetValue<string>("HttpClientBasicConfig:HttpClientName")
        ?? MagicStrings.HttpClientName);
   }
}

What I would like is to have this _config.GetValue<string>("HttpClientBasicConfig:HttpClientName") ?? MagicStrings.HttpClientName) moved into MagicStrings class something like this:

internal class MagicStrings
{
    private readonly IConfiguration _config = null!;

    public MagicStrings(IConfiguration config) => (_config) = (config);

    public const string HttpClientName =
        _config.GetValue<string>("HttpClientBasicConfig:HttpClientName")
        ?? "X_HttpClient";
  or
    public static readonly string HttpClientName2 =
        _config.GetValue<string>("HttpClientBasicConfig:HttpClientName")
        ?? "X_HttpClient";
...

So I can used it like MagicStrings.HttpClientName in the entire app

Share Improve this question edited 19 hours ago Steven 173k25 gold badges349 silver badges449 bronze badges asked 20 hours ago sTxsTx 1,25113 silver badges35 bronze badges 3
  • It's not possible with const, unless you have some tool to update the value in code for each constant shortly before compile, and then any changes to the config won't be reflected once the application is compiled. – ProgrammingLlama Commented 20 hours ago
  • 2 Anyway, it seems a trivial case of calling some code to initialize the values during application start up. I'm not really following what you're needing help with. – ProgrammingLlama Commented 20 hours ago
  • don't really know how to do it to achieve what I want, I tried to make private static IConfiguration _config and initialize the HttpClientName2 value in a static constructor but kind feels like not a good way to do it – sTx Commented 19 hours ago
Add a comment  | 

2 Answers 2

Reset to default 3

@Ivan Petrov answer did the job, also his answer made me thing using options pattern with default values for fields which looks like this:

public class PVO_HttpClientBasicConfig
{
    public string HttpClientName { get; set; } = "PVO_HttpClient";
...
}

So if there is no key of HttpClientName in appsettgins.json it will use the default value from class definition -> this won't work for null values in appsettings.json

I think it's more idiomatic to use AddInMemoryCollection:

builder.Configuration.AddInMemoryCollection(new Dictionary<string, string>
{
     {$"{nameof(HttpClientBasicConfig)}:{nameof(HttpClientBasicConfig.HttpClientName)}",MagicStrings.HttpClientName }
});

And then you need to re-add the defaults (other config that fit your case) which might be:

builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
       .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();

This way you will fall back on the MagicStrings constants whenever you haven't setup anything via appsettings/environment variables. So in your consuming code you won't need to make any checks and can use either IOptions<TOptions> or directly IConfiguration.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论