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"
},
}
IOptions<ConnectionStrings>
into the controller's constructor, not into theIndex()
action. By defining it as an action parameter, you're expecting theModelBinder
to construct it for you (and obviously, it cannot). – haim770[FromServices]
- i.e.public IActionResult Index([FromServices] IOptions<ConnectionStrings> optionsAccessor)
. – serpent5