Last active
August 29, 2015 14:08
-
-
Save lodejard/7e2889abb3c15562871b to your computer and use it in GitHub Desktop.
Example of binding POCO values from IConfiguration instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"demoApp": { | |
"contactPageTagline": "Hello contact page" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Here's the app-settings POCO | |
namespace DemoWebApp | |
{ | |
public class DemoAppOptions | |
{ | |
public string BaseAddress { get; set; } | |
public string ContactPageTagline { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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