Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A field initializer cannot reference the non-static field, method, or property 'MyController._config'

I’m trying to get value from appsettings to MyController in .Net Core 3.1 MVC. Here I need to achieve this in below way:

private readonly IConfiguration _config;

public MyController(IConfiguration config)
{
    _config = config;
}

public string apiURL = _config.GetValue<string>("ServiceURL");

But when I try to do so, I’m getting below error.

A field initializer cannot reference the non-static field, method, or property ‘MyController._config’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

Change your field to be a property instead, like this:

public string apiURL => _config.GetValue<string>("ServiceURL");

When using = you are creating a field.

When using => you are creating a get-only property.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading