Search code examples
c#jsonconfiguration

"Cannot create instance of type 'System.String' because it is missing a public parameterless constructor."


I am trying to implement the options-pattern and get the following error:

"Cannot create instance of type 'System.String' because it is missing a public parameterless constructor."

My setup is as this:

I have a Controller class like this:

public class MyController : Controller
{

  private readonly HttpClient _httpClient;
  private readonly MyConfig _myConfig;

  public MyController(HttpClient httpClient, IOptions<MyConfig> myConfig){
    _httpClient = httpClient;
    _myConfig = myConfig.Value;  <<<<<<<<<<<< FAILS HERE
  }

  [HttpGet]
  public async Task<IActionResult> Get(){
  ....
  var myHttpRequest = new HttpRequestMessage(HttpMethod.Get, _myConfig.MY_ENDPOINT);
  ...
  ...
  }
}

I have a JSON file - my appsettings that goes something like this:

{
"Tracer": {
"Trace": {
  "Default": "",
  "Smari": ""
  }
},

"MY_DB": "",
"MY_USER": "",
"MY_PW": "",
"MY_ENDPOINT": "https://my-test-site/offering",
"MY_CIGO": ""
}

And in my Startup.cs I've written the following:

services.Configure<MyConfig>(Configuration);

Lastly my MyConfig class that goes like this:

public class MyConfig 
{
    public string MY_ENDPOINT { get; set; }
}

Can anyone see, why it fails? I've checked my JSON file for syntax and it seems correct, so I am a bit lost.


Solution

  • Following up on the chat discussion:

    The issue was that the controller got instantiated inside of a test project by a helper class. This helper class expected an appsettings file with a given name (appsettings.test.json). But the test project didn't contain an appsettings file with the expected name. So adding an appsettings file with the correct name solved this issue.

    Means for everyone else getting this error:
    This error most likely occurs if something is wrong with the appsettings.json file. Either being it a format issue or the file not being existent at all. So check for the right filename and format (even if json validators validate it successfully).