ASP.NET Core 2 中的问题配置选项

Posted

技术标签:

【中文标题】ASP.NET Core 2 中的问题配置选项【英文标题】:Issue configuring options in ASP.NET Core 2 【发布时间】:2018-10-08 18:49:59 【问题描述】:

在我的项目上配置选项时,我遇到了这个错误:

System.InvalidOperationException:无法创建类型为“Microsoft.Extensions.Options.IOptions`1[[myproject.Models.ConnectionStrings,]”的实例。模型绑定的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。或者,给“optionsAccessor”参数一个非空的默认值。

有什么想法吗?

我将模型配置如下:

namespace myproject.Models

  public class ConnectionStrings
  
    public ConnectionStrings()
    
        AzureStorageConnectionString = "azurestorageconnectionstring_ctor";
    
    public string AzureStorageConnectionString  get; set; 
  

Startup.cs ConfigureServices(IServiceCollection services) 包含以下两行

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

我的控制器包含这个

private ConnectionStrings _connectionStrings;
public IActionResult Index(IOptions<ConnectionStrings> optionsAccessor)

  _connectionStrings = optionsAccessor.Value;
  return View();

我的 appsettings.json 和 appsettings.Development.json 都包含以下内容


 "Logging": 
 "LogLevel": 
   "Default": "Debug",
   "System": "Information",
   "Microsoft": "Information"
  
 ,
 "ConnectionStrings": 
   "AzureStorageConnectionString": "xxxxxxxxx"
 ,

【问题讨论】:

您应该将IOptions&lt;ConnectionStrings&gt; 注入控制器的构造函数,而不是注入Index() 操作。通过将其定义为操作参数,您期望 ModelBinder 为您构建它(显然,它不能)。 你也可以用[FromServices]来装饰参数 - 即public IActionResult Index([FromServices] IOptions&lt;ConnectionStrings&gt; optionsAccessor) 【参考方案1】:

您应该将IOptions&lt;ConnectionStrings&gt; 注入控制器的构造函数,而不是注入Index() 方法。

通过将其定义为操作参数,您期望 ModelBinder 为您构造它(显然,它不能)。

见Documentation

【讨论】:

以上是关于ASP.NET Core 2 中的问题配置选项的主要内容,如果未能解决你的问题,请参考以下文章