.NET CORE 3.0新增了Worker Services的新項目模板,可以編寫長時間運行的后台服務,並且能輕松的部署成windows服務或linux守護程序。
讀取appsettings.json配置文件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"sqlserverContext": "sqlserverContextvalue",
"mysqlContext": "mysqlContextvalue"
}
}
讀取ConnectionStrings
Main方法中添加代碼
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json",true,true); IConfigurationSection conf = builder.Build().GetSection("ConnectionStrings"); AppSettings.SetAppSetting(conf); CreateHostBuilder(args).Build().Run(); }
第一個GetSection定位第一層位置,比如ConnectionStrings,
第二個GetSection定位第二層位置,選擇ConnectionStrings中的sqlserverContext或mysqlContext
新建AppSettings類
public class AppSettings { private static IConfigurationSection appSection = null; /// <summary> /// 獲取配置文件 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetAppSeting(string key) { if (appSection.GetSection(key) != null) { return appSection.GetSection(key).Value; } else { return ""; } } /// <summary> /// 設置配置文件 /// </summary> /// <param name="section"></param> public static void SetAppSetting(IConfigurationSection section) { appSection = section; } }
private string ConnStr = AppSettings.GetAppSeting("mysqlContext");