Reputation: 15219
I have an ASP.NET Core 2 application hosted on Azure, and I added a new Application Settings MyNewSetting
for my App in the Azure Portal.
How do I access that setting from a controller?
My code bellow:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AppSecrets>(Configuration);
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
//...
My Controller:
public class RecordController : Controller
{
const int MyNewSetting = 7; // this one to replace with Azure Setting one
private readonly ITableRepositories repository;
public RecordController(ITableRepositories rep) {
repository = rep;
}
Here, I need probably to add FromServices
injection, but I am not sure if it will work...
EDIT:
Folowing the @dee_zg answer, the following code could probably do the job:
public class RecordController : Controller
{
int MyNewSetting = 7;
private readonly ITableRepositories repository;
public RecordController(ITableRepositories rep) {
repository = rep;
int myInt;
if (int.TryParse(System.Environment.GetEnvironmentVariable("MY_NEW_SETTING"),
out myInt)) {
MyNewSetting = myInt;
};
}
Upvotes: 1
Views: 355
Reputation: 15551
There's quite a few things you can do.
The options pattern uses custom options classes to represent a group of related settings. We recommended that you create decoupled classes for each feature within your app.
IOptionsSnapshot
supports reloading configuration data when the configuration file has changed. It has minimal overhead. UsingIOptionsSnapshot
withreloadOnChange: true
, the options are bound toConfiguration
and reloaded when changed.
In short, have a look at Configuration in ASP.NET Core, determine the scenario that best fits your needs and have at it!
Hope this helps.
Upvotes: 0
Reputation: 15191
You can choose to either get them from AppSettings["your-key"]
collection or as environment variables: Environment.GetEnvironmentVariable("your-key")
.
From there you can map them to your custom IOptions and inject wherever you need them.
Upvotes: 2