我很熟悉将appsettings.json部分加载到.NET Core startup.cs中的强类型对象中 . 例如:
public class CustomSection
{
public int A {get;set;}
public int B {get;set;}
}
//In Startup.cs
services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));
//Inject an IOptions instance
public HomeController(IOptions<CustomSection> options)
{
var settings = options.Value;
}
我有一个appsettings.json部分,其键/值对随着时间的推移会在数量和名称上有所不同 . 因此,对类中的属性名称进行硬编码是不切实际的,因为新的键/值对需要在类中进行代码更改 . 一些键/值对的小样本:
"MobileConfigInfo": {
"appointment-confirmed": "We've booked your appointment. See you soon!",
"appointments-book": "New Appointment",
"appointments-null": "We could not locate any upcoming appointments for you.",
"availability-null": "Sorry, there are no available times on this date. Please try another."
}
有没有办法将此数据加载到MobileConfigInfo Dictionary对象中,然后使用IOptions模式将MobileConfigInfo注入控制器?
8 回答
您可以在
startup.cs
类中使用Configuration.Bind(settings);
你的设置类就像
希望能帮助到你!
使用这种结构格式:
使您的设置类看起来像这样:
然后这样做
对于想要将其转换为 Dictionary 的其他人,
appsettings.json中的示例部分
以下代码应放在Startup文件> ConfigureServices方法中:
现在您可以从以下任何地方访问字典:
一个缺点是所有值都将作为字符串检索,如果您尝试任何其他类型,该值将为null .
对于简单(可能是微服务)应用程序,您只需将其作为单例
Dictionary<string, string>
添加,然后将其注入到您需要的任何位置:用法:
我相信你可以使用以下代码:
作为ASP.Net Core 2.1中更复杂绑定的示例;根据the documention,我发现使用
ConfigurationBuilder
.Get<T>()
方法更容易使用 .我在
Startup
方法中绑定了配置 .这绑定了
appsettings
文件:进入这个配置结构:
我用下面的方法:
appsettings.json:
startup.cs:
用法:
到目前为止,最简单的方法是将配置类定义为从要支持的Dictionary类型继承 .
然后,您的启动和依赖注入支持将与任何其他配置类型完全相同 .