一佳一

记录像1+1一样简洁的代码

导航

.net6 类库 读取appsettings.json

Posted on 2024-05-29 14:58  一佳一  阅读(143)  评论(0编辑  收藏  举报

类库项目引入 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json程序包

以Sqlsugar读取配置文件为例:

public class SqlsugarBase
    {

        public static IConfiguration Configuration { get; set; }
        static SqlsugarBase()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载            
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            //根据环境变量读取配置
            //Add(new JsonConfigurationSource { Path = $"appsettings.{System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", ReloadOnChange = true })
            .Build();
        }
        
        public SqlSugarClient db => GetInstance();
        SqlSugarClient GetInstance()
        {
            var db = new SqlSugarClient(
                new ConnectionConfig
                {
                    ConnectionString = Configuration.GetSection("AppSettings").GetSection("ConnectionString").Value,
                    DbType = DbType.SqlServer,//数据库类型
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                }
            );
            return db;
        }
    }

业务层需要使用时,集成一下

 public partial class T_PowerManager : SqlsugarBase
    {
        public T_Power Add(T_Power t_Power)
        {
            return db.Insertable(t_Power).ExecuteReturnEntity();
        }

        public int DeleteByPID(int pID)
        {
            return db.Deleteable<T_Power>().Where(c => c.PID == pID).ExecuteCommand();
        }

        public int Update(T_Power t_Power)
        {
            return db.Updateable<T_Power>(t_Power).ExecuteCommand();
        }

        public T_Power GetByPID(int pID)
        {
            return db.Queryable<T_Power>().Single(c => c.PID == pID);
        }

        public int GetTotalCount()
        {
            return db.Queryable<T_Power>().Count();
        }
  }
}