2
votes

I have a razor component that I want to use a configuration value on, from my appsettings.json file, and I've followed the example here: Inject an IConfiguration

But that doesn't work inside the @code block for me.

My razor component looks like this so far:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

@code {
    private string strValue = Configuration.GetSection("MySection").Value;
}

I get the following error on the Configuration.GetSection line:

A field initializer cannot reference the non-static field, method, or property 'MyComponent.Configuration'

I can apparently use @Configuration outside of the @code section without error.

Am I missing something? I wasn't able to find a post relating to this exact issue, so sorry if this is a duplicate.

1
Another way to load settings stackoverflow.com/a/63583894/1492496. Intellisense also works with this.Brian Parker
This is a standard C# rule/error, nothing to with Blazor.Henk Holterman

1 Answers

5
votes

Try this:

@code {
    private string strValue;
  
  protected override void OnInitialized()
{
    strValue = Configuration.GetSection("MySection").Value;

}
}

You can't define and initialize the variable strValue by calling Configuration.GetSection at the same time. You ordinarily have to define a variable, and then populate it with a value returned by a method call, in the OnInitialized(Async) pair.