Mofid.Moghimi
Mofid.Moghimi

Reputation: 1005

Problem to read from other appsetting file in IConfiguration

I have a webapi project in .net Core 3.1 and also i have 2 appsettings file appsettings.json and appsettingsTest.json

appsettings.json file:

{
"Section": {
"Mofid": "appSettings.json"
}
}

appsettingsTest.json file:

{
"Section": {
    "Mofid": "appSettingsTest.json"
}
}

I wrote this code in constructor of startup.cs class

public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {

        configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettingsTest.json")
            .Build();

        Configuration = configuration;
    }

In controller I injected IOptins<T> and IConfiguration and I have 2 action.

First action read a value of setting with IOptions and other one read a value from IConfiguration

public class WeatherForecastController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly MofidOption _option;

    public WeatherForecastController(
        IOptions<MofidOption> options,
        IConfiguration configuration
        )
    {
        _option = options.Value;
        _configuration = configuration;
    }

    [HttpGet]
    public string Get1()
    {
        return _option.Mofid; //read from appsettingsTest.json
    }


    [HttpGet]
    public string Get2()
    {
        return _configuration["Section:Mofid"]; //read from appsettings.json
    }
}

My problem is that IConfiguration reads from appsettings.json and IOptions reads from appsettingsTest.json

I wanna IConfiguration reads from appsettingsTest.json

How can I do that?

Upvotes: 0

Views: 462

Answers (1)

Deepak Mishra
Deepak Mishra

Reputation: 3183

If you modify the configuration in Startup constructor, you would need to register it with DI framework.

services.AddSingleton<IConfiguration>(Configuration);

You should ideally change the configuration from CreateHostBuilder method.

    public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile("MyConfig.json",
                optional: true,
                reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Upvotes: 2

Related Questions