IConfigureOptions <T>未创建范围选项

LP1*_*P13 6 .net-core coreclr asp.net-core-webapi asp.net-core-2.0

通常Options是单例。但是,我正在从数据库中构建选项,而Options属性之一是密码,该密码每月都会更改。所以我想创建ScopedOptions的实例。我正在使用IConfigureOptions<T>像下面这样从数据库中构建选项

public class MyOptions
{
   public string UserID {get;set;}
   public string Password {get;set;
}

public class ConfigureMyOptions : IConfigureOptions<MyOptions>
{
    private readonly IServiceScopeFactory _serviceScopeFactory;
    public ConfigureMyOptions(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public void Configure(MyOptions options)
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var provider = scope.ServiceProvider;
            using (var dbContext = provider.GetRequiredService<MyDBContext>())
            {
                options.Configuration = dbContext.MyOptions
                                        .SingleOrDefault()
                                        .Select(x => new MyOptions()
                                        {
                                            UserID = x.UserID,
                                            Password = x.Password
                                        });
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在控制器中使用

    public class HomeController : BaseController
    {
        private readonly MyOptions _options;
        public HomeController(IOptions<MyOptions> option)
        {
            _options = option.Value;
        }

        [HttpGet]
        [Route("home/getvalue")]
        public string GetValue()
        {
            // do something with _options here
            return "Success";
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想MyOptions为每个新请求创建一个实例,因此将其注册为Scopedstartup.cs

services.AddScoped<IConfigureOptions<MyOptions>, ConfigureMyOptions>();
Run Code Online (Sandbox Code Playgroud)

但是,当我将调试器放入ConfigureMyOptions的Configure方法中时,对于第一个请求,它只会被命中一次。对于下一个请求,容器将返回相同的实例(如单例)。

如何在此处设置范围,以便为每个请求创建MyOptions?

Set*_*Set 5

使用IOptionsSnapshot而不是IOptions在您的控制器中,它将根据请求重新创建选项。


为什么不适用于IOptions

Configuration API 的.AddOptions扩展方法将OptionsManager实例注册为单进程IOptions<>

services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));
services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>)));
Run Code Online (Sandbox Code Playgroud)

OptionsManager类在内部使用缓存

 public virtual TOptions Get(string name)
 {
     name = name ?? Options.DefaultName;

     // Store the options in our instance cache
     return _cache.GetOrAdd(name, () => _factory.Create(name));
 }
Run Code Online (Sandbox Code Playgroud)

github 上的以下问题有助于在上面找到:OptionsSnapshot should always be recreated per request