Reputation: 14088
I started some basic project on .net Core 1.1, and I wish to map some properties from appsettings.json to object, but I probably can't understand correct name convention or something pretty basic
Regarding MSDN Using Options and configuration objects section, it is very easy to use it. I added next lines to appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"XXXOptions": {
"X1": {
"AppId": "11",
"AppCode": "22"
},
"X2": {
"AppId": "",
"AppCode": ""
}
}
}
I added custom class
public class XXXOptions
{
public XXXOptions()
{
}
public X1 X1{ get; set; }
public X2 X2{ get; set; }
}
public class X1
{
public int AppId { get; set; }
public int AppCode { get; set; }
}
public class X2
{
public int AppId { get; set; }
public int AppCode { get; set; }
}
I added next code to Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
// Register the IConfiguration instance which MyOptions binds against.
services.Configure<XXXOptions>(Configuration);
// Add framework services.
services.AddMvc();
}
public class XXXController : Controller
{
private readonly XXXOptions _options;
public XXXController(IOptions<XXXOptions> optionsAccessor)
{
_options = optionsAccessor.Value;
}
public IActionResult Index()
{
var option1 = _options.X1;
return Content($"option1 = {option1.AppCode}, option2 = {option1.AppId}");
return View();
}
}
optionsAccessor.Value - Value containes null values at XXXController constructor.
but it seems like framework show mappet values at JsonConfigurationProvider inside of Configuration property
any ideas?
Upvotes: 2
Views: 5780
Reputation: 11544
In ConfigureServices
method change:
services.Configure<XXXOptions>(Configuration);
to
services.Configure<XXXOptions>(Configuration.GetSection("XXXOptions"));
Upvotes: 7