简体   繁体   中英

Issue configuring options in ASP.NET Core 2

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"
 },
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM