如何在.NET Core中将实例化对象注册为IOptions

问题描述 投票:0回答:1

我有一个 consul 服务器,我正在使用它的键/值功能来集中我的配置。所以,我有一个这样的关键值:

"appSetting": {
    "secret": "my-secret",
    "clientKey" : "my-key",
    "apiVersion" : "V2"
}

我将通过此代码片段读取此配置并将其填充到类型为

AppSetting
:

的对象中
 var appSetting = new AppSetting();
 var queryResult = await _client.KV.Get(configKey);

 if (queryResult.StatusCode == HttpStatusCode.OK)
 {
      var jsonValue = Encoding.UTF8.GetString(queryResult.Response.Value);
      appSetting = JsonSerializer.Deserialize<T>(jsonValue);
 }

然后我想将此变量注册为

IOptions
到我的 DI 容器中,如下所示:

services.Configure<AppSettings>(settings =>
    {
        settings = appSettings
     });

但它不起作用,我的

IOptions
在我的消费者类中是空的。

我确信我从领事处正确读取了设置。

如何解决这个问题?

asp.net-core .net-core consul ioptions
1个回答
0
投票

尝试使用Options.Create

围绕 TOptions 实例创建包装器,以将其自身作为 IOptions 返回。

services.AddSingleton(serviceProvider =>
{
    return Options.Create(appSetting);
});

结果:

© www.soinside.com 2019 - 2024. All rights reserved.