How to bind list of Enviroment Variables to Options in .NET

32 Views Asked by At

I have a list of environment variables located on kubernetes pod where my application is hosted, it`s have no sections, only list of variables that looks like this:

KAFKA_BOOTSTRAP_SERVERS
KAFKA_PASSWORD
KAFKA_TOPIC
KAFKA_USERNAME

what is best way to map it to my options class

[ConfigurationKeyName("KAFKA_BOOTSTRAP_SERVERS")]
public required string BootstrapServers { get; set; }
[ConfigurationKeyName("KAFKA_USERNAME")]
public required string Username { get; set; }
[ConfigurationKeyName("KAFKA_PASSWORD")]
public required string Password { get; set; }
[ConfigurationKeyName("KAFKA_TOPIC")]
public required string Topic { get; set; }

I tries to bind via IConfigureOptions<KafkaOptions> via interface, but its demanding ConfigurationSection to bind for, that i don't have

_configuration
     .GetSection(SectionName)
      .Bind(options);

Can anyone know how to solve it?

1

There are 1 best solutions below

0
Guru Stron On BEST ANSWER

Just bind from the config itself (requires Microsoft.Extensions.Configuration.Binder):

public void Configure(TestOptions options)
{
    _configuration.Bind(options);
}

Personally I would use the double underscore separator (__, see the docs) after KAFKA which would allow to use KAFKA as section (env variables should look like: KAFKA__BOOTSTRAP_SERVERS etc.):

// in the IConfigureOptions
_configuration.GetSection("KAFKA").Bind(options);

// in the settings class
[ConfigurationKeyName("BOOTSTRAP_SERVERS")]
public required string BootstrapServers { get; set; }
[ConfigurationKeyName("USERNAME")]
public required string Username { get; set; }
// ...