IOptionsBuilder <t>。配置从未成功

时间:2019-05-03 20:42:26

标签: c# asp.net-core dependency-injection

我正在开发Web api服务以及该服务的一些扩展。我需要一些自定义选项,因此我尝试使用DI机制。我在波纹管中添加了一个命名选项。但是,选项属性评估行从未成功。

services.AddOptions<TCustomPOCOClass>("PassLineDataTrackerOptions")
.Configure(o =>
{
  o.LocationEventInterval = TimeSpan.FromSeconds(5); // this line never hits
});

1 个答案:

答案 0 :(得分:0)

1)Configure仅在使用选项时被调用。

2)仅在特定情况下才将名称传递给AddOptions。您可以详细了解here

未命名选项示例:

//in Startup.cs
services.AddOptions<MyOptionsClass>()
.Configure(o =>
{
    o.Data = "test";
});

//then in the controller
public MyController(IOptionsMonitor<MyOptionsClass> optionsAccessor)
{        
    //note: Configure is called as MyController gets created by DI
    var data = optionsAccessor.CurrentValue.Data;
}

命名选项示例:

//in Startup.cs
services.AddOptions<MyOptionsClass>("optionalOptionsName")
.Configure(o =>
{
    o.Data = "test";
});

var monitor = services.BuildServiceProvider()
    .GetService<IOptionsMonitor<MyOptionsClass>>();

//note: Configure gets called on .Get
var myOptions = monitor.Get("optionalOptionsName");