- 場景一些配置需要經常用到可以嘗試把配置配置到配置類中需要使用時只需要通過構造函數注入配置類即可。
- json文件結構示例
"SmsSetting": { //253 "Host": "123", "Account": "123", "Password": "123", "Sign": "123",//標簽 //夢網 "MonYunHost": "123", "Userid": "123", "Pwd": "123", //華為 "HuaWeiHost": "123", "AppKey": "123", "AppSecret": "123",//app密鑰 "TemplateId": "123",//模板Id "Sender": "123",//短信通道 "StatusCallBack": "" },
- 配置類示例
public class SmsSettingConfigModel : IConfigModel { #region 253 創藍 public string Host { get; set; } public string Account { get; set; } public string Password { get; set; } /// <summary> /// 簽名 /// </summary> public string Sign { get; set; } #endregion #region 夢網 /// <summary> /// 夢網的地址 /// </summary> public string MonYunHost { get; set; } /// <summary> /// 長度最大6個字符,統一大寫,如提交參數中包含apikey,則可以不用填寫該參數及pwd,兩種鑒權方式中只能選擇一種方式來進行鑒權 /// </summary> public string Userid { get; set; } /// <summary> /// 定長小寫32位字符,如提交參數中包含apikey,則可以不用填寫該參數及userid,兩種鑒權方式中只能選擇一種方式來進行鑒權。密碼規則詳見 /// </summary> public string Pwd { get; set; } /// <summary> /// 32位長度,由夢網提供,與userid及pwd一樣用於鑒權,如提交參數中包含userid及pwd,則可以不用填寫該參數 /// </summary> //public string Apikey { get; set; } #endregion #region 華為 /// <summary> /// 華為地址 /// </summary> public string HuaWeiHost { get; set; } /// <summary> /// APP_Key /// </summary> public string AppKey { get; set; } /// <summary> /// AppSecret /// </summary> public string AppSecret { get; set; } /// <summary> /// 通道號 /// </summary> public string Sender { get; set; } /// <summary> /// 模板ID /// </summary> public string TemplateId { get; set; } /// <summary> /// 選填,短信狀態報告接收地址,推薦使用域名,為空或者不填表示不接收狀態報告 /// </summary> public string StatusCallBack { get; set; } #endregion } public interface IConfigModel { }
- 注入核心代碼
/// <summary> /// 添加configuration到配置類 /// </summary> /// <param name="services"></param> private static void AddConfiguration(this IServiceCollection services) { var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(oo => oo.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IConfigModel)))) .ToArray(); foreach (var type in types) { services.AddSingleton(type, provider => { var sectionName = type.Name.Replace("ConfigModel", "");//截取相關代碼配置類截取次部分和配置根節點匹配 var config = provider.GetService<IConfiguration>(); var model = config.GetSection(sectionName).Get(type); return model; }); } }
- 最終startup 進行注入 services.AddConfiguration();
- 實際使用通過構造函數注入SmsSettingConfigModel中的所有熟悉都有值了
SmsSettingConfigModel _smsSetting; IHttpClientFactory _httpClientFactory; public ChuangLanSendMessage( SmsSettingConfigModel smsSetting, IHttpClientFactory httpClientFactory) { _smsSetting = smsSetting; _httpClientFactory = httpClientFactory; }