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 modify IOptions before injection?

I’m using .NET 7 Preview and I am storing a secret as an environment variable and trying to assign it to a class I’m injecting with IOptions.

I have my other, non-secret parameters stored in appsettings.json:

"MyServerName": {
    "EnvironmentName": "MyServerName",
    "EndpointAddress": "net.tcp://MyServerName:8201/Services/"
}

My configuration binding class is this:

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

public class MyEnvironment
{
    public string EnvironmentName { get; set; }
    public string EndpointAddress { get; set; }
    public string AzureAuthRelayConStr { get; set; }
    public string AzureStorageConnectionStr { get; set; }
}

In my Program.cs:

var MyEnvironment = new MyEnvironment();
builder.Configuration.GetSection(machineName).Bind(MyEnvironment);

// Here is the problem. This doesn't persist. I know I can add this to the constructor, but what's the proper
// method of making changes before binding?
MyEnvironment.AzureStorageConnectionStr = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

builder.Services.Configure<MyEnvironment>(builder.Configuration.GetSection(machineName));

The second to last line is what I’m trying to solve, but it doesn’t persist. I realize I can probably add those other parameters to the constructor, but my question is what’s the proper way to modify them before binding or is it possible?

Is there a way to pass a List to IOptions or just some generic parameters without declaring a custom class with a JSON?

>Solution :

You can use this:

builder.Services.Configure<MyEnvironment>(options =>
{
    builder.Configuration.GetSection(machineName).Bind(options);

    options.AzureStorageConnectionStr = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
});
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