'Set configuration and options from json file for servicebuilder in test project

Hi i am trying to configure and build services in a test project. I have read and built a json file into IConfigurationRoot, and can extracts specific parts individually and bind them to IOptions using services.Configure(config.GetSection("MySection"));

I would like to know if there is a clean way to do this for the root configuration instead of having to bind a section to a specific type?



Solution 1:[1]

I'd suggest binding the whole configuration to an object

// Program.cs
var host = Host // Use your desired host and builder here
  .CreateDefaultBuilder(args)
  .ConfigureServices((context, services) => services
    .AddOptions<AppConfig>()
    .Bind(context.Configuration)
  )
  .Build();

public record AppConfig(string Prop1, int Prop2, AppConfig.Db DbConfig){
  public record Db(string ConnectionString);
}
// appsettings.json
{
  "Prop1": "aaa",
  "Prop2": 69
  "Db": {
    "ConnectionString": "xxx"
  }
}

You can also override the values with environment variables. Passing Db__ConnectionString=yyy as an environment variable will take precedence and the resulting value in AppConfig.Db.ConnectionString will be "yyy".

Accessing the configuration is then done through one of IOptions<T>, IOptionsSnapshot<T> or IOptionsMonitor<T>

// YourService.cs
internal class YourService: IYourService {

  private readonly IOptionsSnapshot<AppConfig> appConfig;

  public YourService(IOptionsSnapshot<AppConfig> appConfig){
    this.appConfig = appConfig;
  }

  public async Task DoWorkAsync(){
    var connectionsString = this.appSettings.Value.Db.ConnectionString;
    await this.UseConnectionStringAsync(connectionString);
  }
}

See https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-6.0 for further information.

Hope this helps a little ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heehaaw