Search code examples
c#blazorblazor-server-side

How to import IConfiguration in Blazor server side razor component?


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.


Solution

  • 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.