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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With