Make sure the json file is set to copy to directory as discussed in this blog. Otherwise when you build or debug the configuration file won’t be included. Make sure you change it in the properties.
The reason you are not able to access your configuration, is because the IConfigurationRoot does not reference the dependency for ConfigurationBuilder. To ensure that your configuration content will load, would be to do something along these lines:
public static class ConfigurationProvider
{
public static IConfiguration BuildConfiguration => new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.Build();
}
The above will build our configuration, now we should use the configuration.
public static class ServiceProvider
{
public static IServiceProvider BuildServiceProvider(IServiceCollection services) => services
.BuildDependencies()
.BuildServiceProvider();
}
Once we have defined our provider, we can do the following so we can pass our IConfiguration around the application to access the objects.
var serviceCollection = new ServiceCollection()
.AddSingleton(configuration => ConfigurationProvider.BuildConfiguration());
var serviceProvider = ServiceProvider.BuildServiceProvider(serviceCollection);
Then inside of another class, you would have the following:
public class SampleContext : ISampleRepository
{
private readonly string dbConection;
public SampleContext(IConfiguration configuration) => configuration.GetConnectionString("dbConnection");
...
}
Then our appsettings.json would look like this:
{
"ConnectionStrings": {
"dbConnection": "..."
}
}
The above is the correct format for a json object. If you have a nested object along these lines:
{
"Sample" : {
"Api" : {
"SampleGet" : "..."
}
}
}
Then your C# would be:
configuration.GetSection("Sample:Api")["SampleGet"];
The above is based on the assumption your configuration and usage are not in the same sequential area, ie directly in your main. Also you should use appsettings.json since that is the default, less extra wiring if I remember correctly. Your json also needs to be correctly formatted.
But that will definately work, if you need more help let me know and I can send you some sample console core applications to demonstrate usage.
{"Name":{"beep":"boop"}}. Then you can sayconfig.GetSection("Name").appsettings.jsonhowever you want. Konrad, are you doing that code directly in main or are you leveraging any other aspects of core? Such asIServiceCollection?