I have added the access to the appsettings.json file as a framework service in my Startup.cs:
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.Configure<AppConfig>(Configuration);
services.AddMvc();
}
So now I have access to the configuration file from my controllers:
public class HomeController : Controller
{
private readonly AppConfig _appConfig;
public HomeController(IOptions<AppConfig> appConfig, ConfigContext configContext)
{
_appConfig = appConfig.Value;
}
}
That's working but what's currently a good practice in netcoreapps for accessing the config file from classes outsite my controller scope?
I mean that I would not like to pass always the required config variables to other methods, example:
public IActionResult AnyAction() {
SomeStaticClass.SomeMethod(_appConfig.var1, _appConfig.var2, _appConfig.var3...)
//or always have to pass the _appConfig reference
SomeStaticClass.SomeMethod(_appConfig)
}
In previous versions of .NET Framework if I required access to the config file from "SomeStaticClass" I used to use ConfigurationManager in any class that I need access to the web.config.
What's the correct way to do it in a netcoreapp1.1 ? either ConfigurationManager like or dependency injection approach works for me.