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

C# access configuration settings during ConfigureServices

Is there a working method accessing configuration values during ConfigureServices() in C# netCore? I have a dapr settings added as ‘options pattern’, but need the values in the same section immediately.

var builder = WebApplication.CreateBuilder(args);

builder.Host.ConfigureServices((ctx, services) =>
{
    services.ConfigureOptions<DaprConfigConfigBinder>();
    var daprSettings = ctx.Configuration.Get<DaprConfig>(); // ????
    var daprClient = new DaprClientBuilder().UseGrpcEndpoint(daprSettings.gcprEndpoint).Build();
}

where

public class DaprConfig
{
    [ConfigurationKeyName("stateStoreName")]
    public string stateStoreName { get; set; } = null!;

    [ConfigurationKeyName("gcprEndpoint")]
    public string gcprEndpoint { get; set; } = null!;
}

internal class DaprConfigConfigBinder : IConfigureOptions<DaprConfig>
{
    private const string SECTION_NAME = "Dapr";
    private readonly IConfiguration config;

    public DaprConfigConfigBinder(IConfiguration config)
    {
        this.config = config;
    }

    public void Configure(DaprConfig options)
    {
        this.config.GetSection(SECTION_NAME).Bind(options);
    }
}

and appsettings.json important part is:

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

{
    "Dapr": {
        "stateStoreName": "statestore",
        "gcprEndpoint": "http://127.0.0.1:13109"
    }
}

Thanks in advance!

>Solution :

I would do it like this:

var config= new DaprConfig();
builder.Configuration.GetSection("Dapr").Bind(config);
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