3
votes

While configuring Options on my project I came up across this error :

System.InvalidOperationException: Could not create an instance of type 'Microsoft.Extensions.Options.IOptions`1[[myproject.Models.ConnectionStrings, ]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'optionsAccessor' parameter a non-null default value.

Any idea ?

I configured the model as following :

namespace myproject.Models
{
  public class ConnectionStrings
  {
    public ConnectionStrings()
    {
        AzureStorageConnectionString = "azurestorageconnectionstring_ctor";
    }
    public string AzureStorageConnectionString { get; set; }
  }
}

Startup.cs ConfigureServices(IServiceCollection services) contains the following two lines

services.AddOptions();
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

My controller contains this

private ConnectionStrings _connectionStrings;
public IActionResult Index(IOptions<ConnectionStrings> optionsAccessor)
{
  _connectionStrings = optionsAccessor.Value;
  return View();
}

And both my appsettings.json and appsettings.Development.json consist of the following

{
 "Logging": {
 "LogLevel": {
   "Default": "Debug",
   "System": "Information",
   "Microsoft": "Information"
  }
 },
 "ConnectionStrings": {
   "AzureStorageConnectionString": "xxxxxxxxx"
 },
}
1
You're supposed to inject IOptions<ConnectionStrings> into the controller's constructor, not into the Index() action. By defining it as an action parameter, you're expecting the ModelBinder to construct it for you (and obviously, it cannot).haim770
You could also just decorate the parameter with [FromServices] - i.e. public IActionResult Index([FromServices] IOptions<ConnectionStrings> optionsAccessor).serpent5

1 Answers

5
votes

You're supposed to inject IOptions<ConnectionStrings> into the controller's constructor, not into the Index() method.

By defining it as an action parameter, you're expecting the ModelBinder to construct it for you (and obviously, it cannot).

See Documentation