Memory Configuration Source

The following example uses a MemoryConfigurationSource to supply additional configuration:

Program.Main:

using Microsoft.Extensions.Configuration.Memory;

...

var vehicleData = new Dictionary<string, string>()
{
    { "color", "blue" },
    { "type", "car" },
    { "wheels:count", "3" },
    { "wheels:brand", "Blazin" },
    { "wheels:brand:type", "rally" },
    { "wheels:year", "2008" },
};

var memoryConfig = new MemoryConfigurationSource { InitialData = vehicleData };

...

builder.Configuration.Add(memoryConfig);

Inject an IConfiguration instance into a component to access the configuration data:

@page "/"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1>Configuration example</h1>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>

@code {
    protected override void OnInitialized()
    {
        var wheelsSection = Configuration.GetSection("wheels");
        
        ...
    }
}

Example:

            // Custom App Configuration
            var appData = new Dictionary<string, string>()
            {
                { "MyHost", "https://abc.com" },
            };

            var memoryConfig = new MemoryConfigurationSource { InitialData = appData };

            builder.Configuration.Add(memoryConfig);
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<p>MyHost: @Configuration["MyHost"]</p>
using Microsoft.Extensions.Configuration;

[Inject]
public IConfiguration Configuration { get; set; }

Console.WriteLine("MyHost: " + Configuration["MyHost"]);

Sources:

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-5.0

Last modified: December 13, 2020

Author

Comments

Write a Reply or Comment