English 中文(简体)
• 如何将瞬时物体登记为代谢。 NET Core
原标题:How to register an instantiated object as IOptions in .NET Core

我有一台配置服务器,我正在利用其关键/价值功能集中我的组合。 因此,我具有关键价值:

"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在我的消费类别中是空的。

我确信,我是从座右铭读一下。

How can I resolve this issue?

问题回答

Try to use Options.Create :

• 围绕一个征兆创建一个包裹,把自己作为共犯。

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

结果:

“在此处的影像描述”/</a





相关问题
Blazor Server App : Unable to unprotect the message.State

I am getting an Exception as above in my Blazor server application. Below is my Program.cs File builder.Services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme) .AddOpenIdConnect(...

System Text JsonSerializer Deserialization of TimeSpan

In researching how to deserialize a TimeSpan using Newtonsoft s JSON.net I came across code in my current project that did not use Json.net. It used System.Text.Json.JsonSerializer and appeared to not ...

TCP Connection Creation and Closing Event Hooking [closed]

What helper classes C# provides to monitor all TCP connection on an OS. A piece of Sample code would also be appreciated. Note: Original intent was to monitor this on Windows but would be nice to do ...

热门标签