Reputation: 2281
I'm sure I've got something basic wrong but I can't spot it, sorry. Stepping into the startup code suggests the appsettings.json is being correctly loaded, but the test class then gets null for the config class.
Startup:
public class Startup
{
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder().AddJsonFile("appSettings.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession();
services.Configure<EnvironmentConfig>(Configuration.GetSection("EnvironmentConfig"));
}
}
ConfigTester:
public class ConfigTester
{
private readonly IOptions<EnvironmentConfig> _environmentConfig;
public ConfigTester(IOptions<EnvironmentConfig> environmentConfig)
{
_environmentConfig = environmentConfig;
}
public string ConfigName()
{
return _environmentConfig.Value.Name; //_environmentConfig.Value is set, but Name is null
}
}
EnvironmentConfig:
public class EnvironmentConfig
{
public string Name;
}
appSettings.json:
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"EnvironmentConfig": {
"Name": "develop"
}
}
What have I missed?
Upvotes: 1
Views: 206
Reputation: 93253
When using IServiceCollection.Configure
, the ConfigurationBinder
class that ends up doing the work of binding the values in your appSettings.json
file to your EnvironmentConfig
class only binds against properties. That means all you have to do is change your public field to a public property:
public class EnvironmentConfig
{
public string Name { get; set; }
}
Upvotes: 1
Reputation: 21
Add the following line in your ConfigureServices method before you configure your Options using serives.Configure<T>()
. To use the Options feature you have to enable it.
services.AddOptions();
Upvotes: 2