Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Can anyone know how to solve it?

>Solution :

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; }
// ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading