Tuesday, June 13, 2017

How do I even use stuff I stage in Startup in a .NET Core app beyond Startup?

Let's say you have a IConfigurationRoot in Startup.cs named Configuration which you prep like so per this:

var builder = new ConfigurationBuilder()
   .SetBasePath(env.ContentRootPath)
   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
   .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
   .AddEnvironmentVariables();
Configuration = builder.Build();

 
 

...and, also maybe string Whatever = Configuration["Whatever"]; wherein Whatever is a property in the JSON object inside of appsettings.json. Alright, how can we keep what we pulled out from appsettings in the name of using it in a Controller? I recommend Static State!

 
 

Addendum 6/27/2017: If you need to drill into the json object with the settings, do so with colons in lieu of dots like so:

string Whatever = Configuration["Foo:Bar:Baz:Qux"];

No comments:

Post a Comment