Home > Net >  How to modify IOptions before injection?
How to modify IOptions before injection?

Time:10-29

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:

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?

CodePudding user response:

You can use this:

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

    options.AzureStorageConnectionStr = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
});
  • Related