.net-core - 在 .NET Core 中,如何从 appsetting.json 读取并在 setter 方法中为对象赋值
问题描述
我在 appsettings.json 中有 SendGrid 电子邮件配置,我需要在 startup.cs 中进行初始化,我已经定义了类 EmailConfig,我想在其中分配来自 appsettings.json 的值,以便我可以在其他地方使用。
appsetting.json
"SendGridEmailSettings": {
"SendGrid_API_Key": "MY-Key-XYZ",
"From": "info@organisation.ltd"
}
EmailConfig 类
public class EmailConfig : IEmailConfig
{
public string API_Key { get; set; }
public string From { get; set; }
}
在我的核心课程中,我需要将此值读取为
public mailConfig emailConfig { get; set; }
解决方案
我将首先重命名 EmailConfig 字段以匹配设置:
public class EmailConfig
{
public string SendGrid_API_Key { get; set; }
public string From { get; set; }
}
在您的 startup.cs 的 ConfigureServices 方法中,添加:
var emailConfig = new EmailConfig();
Configuration.GetSection("SendGridEmailSettings").Bind(emailConfig);
此时,emailConfig 对象具有 appsetting.json 值。
如果我可以建议的话,我会创建一个专门用于发送电子邮件的服务,并将 EmailConfig 对象传递给该服务一次:
public class EmailService : IEmailService
{
private readonly EmailConfig _emailConfig;
public EmailService(EmailConfig emailConfig)
{
_emailConfig = emailConfig
}
}
您现在可以通过在您的 startup.cs 的 ConfigureServices 方法中添加以下内容来将 emailConfig 对象发送到服务:
services.AddTransient<IEmailService, EmailService>(_ =>
new EmailService(emailConfig));
推荐阅读
- raster - 如何从 netcdf 文件中获取日期和深度并合并到数据框中?
- node.js - 在 Node.JS 中跨测功机保存对象的最佳方法
- mysql - 将 MySQL 查询复制并粘贴到命令行中不起作用
- google-colaboratory - 可视化对象检测图时 TensorBoard 挂起
- arrays - 如何将文件添加到 bash 数组
- spring - Crontab 无法启动 Maven 服务
- c++ - 连接变量时,目标特定变量定义不起作用
- prometheus - 总结一个已经是比率的指标
- javascript - 通过JS浏览器控制台直接执行代码
- javascript - Electron 在浏览器窗口中使用 ipcRenderer 获取对象选定对象的类名