0

I have used an inmemory database as configurationprovider. I have added the table with id, key and value column and assigned them values in Load function of ConfigurationProvider.

public override void Load()
        {
            this.Data = new Dictionary<string, string?>()
            {
                {"Logging__Console__LogLevel__Default","Trace"}
            };

            using (var db = new ConfigurationDbContext(this._connectionString))
            {
                db.Database.EnsureCreated();
                if (!db.RevisionOption.Any())
                {
                    foreach (var data in Data)
                    {
                        db.RevisionOption.Add(new RevisionConfigurationOption()
                        {
                            Key = data.Key,
                            Value = data.Value ?? "None"
                        });
                    }
                    db.SaveChanges();
                }

                foreach (var data in db.RevisionOption)
                {
                    this.Data.Clear();
                    this.Data.Add(data.Key, data.Value);
                }
            }
        }

I have added the provider in IConfigurationSource

public IConfigurationProvider Build(IConfigurationBuilder builder)
{
    return new RevisionProvider(this._connectionString);
}

In the extension method i have added the Source to IConfiburationBuilder

public static IConfigurationBuilder AddCustomConfiguration(this IConfigurationBuilder builder)
{
    var currentConfiguration = builder.Build();
    var connectionString = currentConfiguration.GetConnectionString("configurationConnectionString");
    builder.Add(new RevisionSource(connectionString));
    return builder;
}

In the Program.cs I have called the method like this

var configuration = new ConfigurationBuilder()
//.AddEnvironmentVariables()
.AddJsonFile($"appsettings{(string.IsNullOrWhiteSpace(environmentName) ? string.Empty : "." + environmentName)}.json")
.AddCustomConfiguration()
.Build();

Next i have created a ServiceCollection object and tried to add the console logger

var serviceProvider = new ServiceCollection()
.AddLogging(loggingBuilder =>
{
    loggingBuilder.ClearProviders()
    .AddConfiguration(configuration.GetSection("Logging"))
    .AddConsole();
})
.BuildServiceProvider();

var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
logger.LogDebug("hello");

Problem is, if i add the key value pair as environment variables {"Logging__Console__LogLevel__Default","Trace"}

then it works. Log is written to the terminal. But using the custom ConfigurationProvider it doesn't.

Saurav
  • 592
  • 4
  • 21

0 Answers0