1

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;
        };
    }

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

There's quite a few things you can do.

  1. Use Options and configuration objects

    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.

  2. Use an IOptionsSnapshot.

    IOptionsSnapshot supports reloading configuration data when the configuration file has changed. It has minimal overhead. Using IOptionsSnapshot with reloadOnChange: true, the options are bound to Configuration and reloaded when changed.

  3. ... (see documentation)

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.

2 Comments

I already saw that documentation before asking the question. Say, I know what to use, I don't know HOW to use, this is why I added some code.
Thanks. I wouldn't ask if the code in example were useful for my case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.