用NetCore作项目若是用EF ORM在网上有不少的配置链接字符串,读取以及使用方法git
因为不少朋友用的其余ORM如SqlSugar,NH,Dapper等,在读取链接字符串的时候,每每把信息保存到一个配置文件中,例如appsetting.json,github
网上有不少关于读取appsetting.json都是经过注入的方式, 在ORM读取配置的时候,都是在一个类库里面,因此用注入的方式有时候不适合【我的理解】数据库
因以上场景,下面这个方法读取配置能够在任何地方使用json
喜欢NetCore的朋友,欢迎加群QQ:86594082app
源码地址:https://github.com/feiyit/SoaProJect测试
一、在项目中,新建一个NetCore的类库,建立类ConfigServicesui
namespace Core.Extensions { /// <summary> /// 读取配置文件 /// </summary> public class ConfigServices { public static IConfiguration Configuration { get; set; } static ConfigServices() { //ReloadOnChange = true 当appsettings.json被修改时从新加载 Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); } } }
二、在Web项目下面appsettings.json里面增长自定义的配置spa
{ "DBConnection": { "MySqlConnectionString": "server=localhost;database=fyt_ims;uid=root;pwd=123456;charset='utf8';SslMode=None" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
三、新建一个读取配置的类3d
namespace FytErp.Core.Model.ConfigModel { /// <summary> /// 数据库链接字符串 /// </summary> public class DBConnection { /// <summary> /// MySql数据库链接字符串 /// </summary> public string MySqlConnectionString { get; set; } /// <summary> /// SqlServer数据库链接字符串 /// </summary> public string SqlServerConnectionString { get; set; } } }
四、编写测试读取配置code
namespace FytErp.Web.Pages { public class IndexModel : PageModel { public DbConnection DbSetting { get; private set; } public void OnGet() { //得到配置文件中的DBConnection节点 DbSetting = ConfigServices.Configuration.GetSection("DbConnection").Get<DbConnection>(); } } }
五、最终读取结果