[英]ASP.NET Core - how to inject IOptionsMonitor<T[]>
How can I inject IOptionsMonitor<T[]>
into a controller?如何将
IOptionsMonitor<T[]>
注入控制器?
In appsettings.json在 appsettings.json 中
{
"MyArray": [
{
"Name": "Name 1",
"SomeValue": "Value 1",
},
{
"Name": "Name 2",
"SomeValue": "Value 2",
}
]
}
In Startup.cs在 Startup.cs 中
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<MyOptions[]>(Configuration.GetSection("MyArray"));
}
In HomeController在家庭控制器中
public class HomeController : Controller
{
private readonly MyOptions[] myOptions;
public HomeController(IOptionsMonitor<MyOptions[]> myOptions)
{
this.myOptions = myOptions.CurrentValue;
}
}
I'm getting Unable to resolve service for type 'Microsoft.Extensions.Options.IOptionsMonitor`1[MyOptions[]]' while attempting to activate 'Api.Controllers.HomeController'.
我
Unable to resolve service for type 'Microsoft.Extensions.Options.IOptionsMonitor`1[MyOptions[]]' while attempting to activate 'Api.Controllers.HomeController'.
exception.例外。
I can access the configuration by configuration.GetSection("MyArray").Get<MyOptions[]>()
and it works, but I would like to inject it as constructor parameter.我可以通过
configuration.GetSection("MyArray").Get<MyOptions[]>()
访问配置并且它可以工作,但我想将它作为构造函数参数注入。
You need to create a class with MyOptions[]
as a property and the inject that class and add the whole configuration without section. 您需要使用
MyOptions[]
作为属性创建一个类,并注入该类并添加整个配置而不添加任何部分。
public class Options
{
public MyOptions[] MyArray { get; set; }
}
Startup.cs Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<Options>(Configuration);
}
HomeController.cs HomeController.cs
public class HomeController : Controller
{
private readonly MyOptions[] myOptions;
public HomeController(IOptionsMonitor<Options> myOptions)
{
this.myOptions = myOptions.CurrentValue.MyArray;
}
}
迟到但可能对其他人有帮助,只需使用
services.Configure<List<SingleObject>>(configuration.GetSection($"Parrent:Array"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.