This article and this other article show how you can map your appsettings to a class in ASP.NET 5.
From the first link:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
services.AddMvc();
}
However, I'm not getting the Configure()
method on services
. So either I'm missing a package, or the API has changed. Which is it?
I'm using RC1. I believe the articles are based on beta 4.
This example should give you what you need. I have this class:
public class UIOptions
{
public UIOptions()
{ }
public int DefaultPageSize_SiteList { get; set; } = 10;
public int DefaultPageSize_CountryList { get; set; } = 10;
public int DefaultPageSize_StateList { get; set; } = 10;
public int DefaultPageSize_RoleList { get; set; } = 10;
public int DefaultPageSize_RoleMemberList { get; set; } = 10;
public int DefaultPageSize_UserList { get; set; } = 10;
public int DefaultPageSize_LogView { get; set; } = 10;
}
If I want to override any of the default values I can add this in my appsettings.json:
"UIOptions": {
"DefaultPageSize_SiteList" : "5"
}
But if I'm not changing anything it doesn't matter if this exists in the appsettings.json file.
In startup I have this:
services.Configure<UIOptions>(Configuration.GetSection("UIOptions"));
In a controller where I need the options injected I have a constructor dependency on
IOptions<UIOptions>
Note that I get my UIOptions instance from the .Value property of the IOptions
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
public class CoreDataController : Controller
{
public CoreDataController(
IOptions<UIOptions> uiOptionsAccessor
)
{
uiOptions = uiOptionsAccessor.Value;
}
private UIOptions uiOptions;
}
Make sure you're using the Microsoft.Extensions.DependencyInjection package. The package names were changes somewhere around beta8