I have a consul server and I am using its key/value functionality to centralize my configuration. so, I have a key value like this:
"appSetting": {
"secret": "my-secret",
"clientKey" : "my-key",
"apiVersion" : "V2"
}
I will read this configuration by this code snippet and fill it into a object with type of 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);
}
And then I want to register this variable as IOptions
into my DI container like this:
services.Configure<AppSettings>(settings =>
{
settings = appSettings
});
but it does not work and my IOptions
is empty in my consumer classes.
I am sure that I am reading the setting correctly from the consul.
How can I resolve this issue?
Try to use Options.Create :
Creates a wrapper around an instance of TOptions to return itself as an IOptions.
services.AddSingleton(serviceProvider =>
{
return Options.Create(appSetting);
});
result: