sTx
sTx

Reputation: 1261

Set Const or static readonly field value from appsettings.json through dependency injection in .net core 9

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

Upvotes: 0

Views: 68

Answers (2)

sTx
sTx

Reputation: 1261

@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

Upvotes: 3

Ivan Petrov
Ivan Petrov

Reputation: 4802

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.

Upvotes: 1

Related Questions