Thursday, April 2, 2020

Use a better ConfigurationBuilder instantiation for getting at appsettings.json variables in .NET Core 3.

Outside of a Controller or PageModel (WebMatrix), I had this trick, but here is a better way to go in modern times. It uses the Microsoft.Extensions.Configuration using declaration.

IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json",
      optional: true, reloadOnChange: true).Build();
string thing = config["Repositories"];

 
 

Oh, it turns out that .AddJsonFile is an extension method from Microsoft.Extensions.Configuration.Json so you need that too. Castle.Core.Configuration may have an IConfiguration also. The name is kinda weak.

No comments:

Post a Comment