鉴于 Config
是一个 IConfiguration
并且 services
是一个 ServiceCollection
,代码如下:
var section = Config.GetSection("MyDatabaseOptions");
var configdb = secao.Get<MyDbConfiguration>();
configdb.ConnectionString = DoSomethingWithSectionObject(configdb);
我想使用 configdb.ConnectionString
的新内容更新 section
,以便能够使用以下方式在 ServiceCollection
上配置它:
services.Configure<MyDbConfiguration>(section);
我怎样才能做到呢?或者还有其他方法?
最佳答案
IConfiguration
只是一个字符串层次结构,其底层有一个路径,因此您可以使用具有正确键的索引器来修改值:
var section = Config.GetSection("MyDatabaseOptions");
var configdb = section.Get<MyDbConfiguration>();
section[nameof(MyDbConfiguration.ConnectionString)] = DoSomethingWithSectionObject(configdb);
但它只适用于字符串,如果你想修改整个结构,会稍微复杂一点,但想法仍然是一样的 - 你需要指定属性和字符串值的路径,例如:
Configuration[$"{section.Path}:{nameof(MyDbConfiguration.ConnectionString)}"] = "new value";
关于asp.net-core - 如何更新(在内存中)IConfigurationSection 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751791/