每天记录一点:NetCore获得配置文件 appsettings.json

用NetCore做项目如果用EF  ORM在网上有很多的配置连接字符串,读取以及使用方法

由于很多朋友用的其他ORM如SqlSugar,NH,Dapper等,在读取连接字符串的时候,往往把信息保存到一个配置文件中,例如appsetting.json,

网上有很多关于读取appsetting.json都是通过注入的方式,  在ORM读取配置的时候,都是在一个类库里面,所以用注入的方式有时候不适合【个人理解】

 

因以上场景,下面这个方法读取配置可以在任何地方使用

 

喜欢NetCore的朋友,欢迎加群QQ:86594082

源码地址:https://github.com/feiyit/SoaProJect

 

1、在项目中,新建一个NetCore的类库,创建类ConfigServices

复制代码
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();
        }
    }
}
复制代码

2、在Web项目下面appsettings.json里面增加自定义的配置

复制代码
{
  "DBConnection": {
    "MySqlConnectionString": "server=localhost;database=fyt_ims;uid=root;pwd=123456;charset='utf8';SslMode=None"
  },  
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
复制代码

 

3、新建一个读取配置的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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; }
    }
}

 

4、编写测试读取配置

复制代码
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>();
        }
    }
}
复制代码

 

5、最终读取结果

 

本文作者:Jason.裕哥

本文链接:https://www.cnblogs.com/fuyu-blog/p/8906060.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Jason.裕哥  阅读(2553)  评论(2编辑  收藏  举报
历史上的今天:
2015-04-22 查找SQL数据表或视图中的字段属性信息
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起