Skip to content

Instantly share code, notes, and snippets.

@lodejard
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lodejard/7e2889abb3c15562871b to your computer and use it in GitHub Desktop.
Save lodejard/7e2889abb3c15562871b to your computer and use it in GitHub Desktop.
Example of binding POCO values from IConfiguration instance
{
"demoApp": {
"contactPageTagline": "Hello contact page"
}
}
// Here's the app-settings POCO
namespace DemoWebApp
{
public class DemoAppOptions
{
public string BaseAddress { get; set; }
public string ContactPageTagline { get; set; }
}
}
// this controller is using an app-settings POCO
using Microsoft.Framework.OptionsModel;
namespace DemoWebApp.Controllers
{
public class HomeController : Controller
{
private readonly DemoAppOptions _demoAppOptions;
public HomeController(
IOptions<DemoAppOptions> demoAppOptions)
{
_demoAppOptions = demoAppOptions.Options;
}
public IActionResult Contact()
{
ViewBag.Message = _demoAppOptions.ContactPageTagline;
return View();
}
}
}
// The Startup class adds a line to ConfigureServices to apply IConfiguration onto DemoAppOptions
namespace DemoWebApp
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime.
public void ConfigureServices(IServiceCollection services)
{
// ---- This is the line which is added
services.Configure<DemoAppOptions>(Configuration.GetSubKey("demoApp"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment