20

The "Configuration" object loads all appsettings.json content successfully (with "CreateDefaultBuilder" in Program.cs). The same "Configuration" object is accessible in "Startup.cs" as well (as it is injected by framework itself).

Now, in "Startup.ConfigureServices", I would like add add more entries to "Configuration" object and access it in "Startup.Configure" and in other classes (like controllers, etc.)

In simple words, I would like to have something like the following:

Configuration.add("MyNewKey", "MyNewValue"); //HOW TO DO THIS

At this moment, I don't want to use any structured types.

Is this possible at all?

2
  • learn.microsoft.com/en-us/aspnet/core/fundamentals/… Commented Jan 17, 2021 at 18:17
  • the values provided for Configuration are pulled from the so-called Configuration sources. We have some built-in configuration sources like json files, ini files, xml files, command arguments, environment variables, in-memory collection. You can of course implement your own custom configuration source. In this case, looks like what you want is in-memory collection. To consume the values, just access them via the configuration keys. Using Options pattern is just a way to consume the configuration conveniently but not required. Commented Jan 17, 2021 at 18:33

2 Answers 2

27

Is this possible at all?

It is possible. We can set a configuration value in the Startup.ConfigureServices method and access it in the "Startup.Configure" and in other classes (like controllers, etc.) You could check the following sample code (Asp.net core 3.1 MVC application):

Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    // using get and set accessor 
    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        Configuration["MyNewKey"] = "AAA";  //set the configuration value.
        services.AddControllersWithViews();
        services.AddRazorPages();
    } 
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        var result = Configuration["MyNewKey"]; //access the configuration value.

        app.UseEndpoints(endpoints =>
        { 
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
            
        });
    }
}

HomeController.cs:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IConfiguration _configuration;

    public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        var value = _configuration["MyNewKey"];
        return View();
    }

The debug screenshot as below:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

I love the way you explained/presented. Simple, Visual and Straight Forward. Thank you so much!
4

You can use the ConfigurationBuilder and the AddInMemoryCollection extension like this:

var inMemorySettings = new Dictionary<string, string> {
   {"YOUR_KEY", "YOUR_VALUE"}
};
    
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(inMemorySettings);
var configuration = configurationBuilder.Build();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.