ASP.NET Core-如何注入IOptionsMonitor <T []>

时间:2019-06-12 07:04:14

标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi

如何将ab gh cd ij ef kl 注入控制器?

在appsettings.json

IOptionsMonitor<T[]>

在Startup.cs

{
      "MyArray": [
       {
          "Name": "Name 1",
          "SomeValue": "Value 1",
       },
       {
          "Name": "Name 2",
          "SomeValue": "Value 2",
       }
      ]
}

在HomeController中

public void ConfigureServices(IServiceCollection services)
{
     services.AddOptions();
     services.Configure<MyOptions[]>(Configuration.GetSection("MyArray"));
}

我正在 public class HomeController : Controller { private readonly MyOptions[] myOptions; public HomeController(IOptionsMonitor<MyOptions[]> myOptions) { this.myOptions = myOptions.CurrentValue; } } 例外。

我可以通过Unable to resolve service for type 'Microsoft.Extensions.Options.IOptionsMonitor`1[MyOptions[]]' while attempting to activate 'Api.Controllers.HomeController'.访问配置,并且可以使用,但是我想将其作为构造函数参数注入。

1 个答案:

答案 0 :(得分:0)

您需要创建一个以MyOptions[]作为属性的类,并注入该类并添加不带节的整个配置。

public class Options
{
    public MyOptions[] MyArray { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddOptions();
     services.Configure<Options>(Configuration);
}

HomeController.cs

public class HomeController : Controller
{
    private readonly MyOptions[] myOptions;
    public HomeController(IOptionsMonitor<Options> myOptions)
    {
        this.myOptions = myOptions.CurrentValue.MyArray;
    }
}