最低要求:
SqlSugar/SqlSugarCore 5.0.3.4
SqlSugarScope 是基于 SqlSugarClient 基础上实现了线程安全机制,推荐单例
推荐直接复制使用
public class SqlSugarHelper //不能是泛型类 { //如果是固定多库可以传 new SqlSugarScope(List<ConnectionConfig>,db=>{}) 文档:多租户 //如果是不固定多库 可以看文档Saas分库 //用单例模式 public static SqlSugarScope Db= new SqlSugarScope(new ConnectionConfig() { ConnectionString = "Server=.xxxxx",//连接符字串 DbType = DbType.SqlServer,//数据库类型 IsAutoCloseConnection = true //不设成true要手动close }, db=> { //(A)全局生效配置点 //调试SQL事件,可以删掉 db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql);//输出sql,查看执行sql //5.0.8.2 获取无参数化 SQL //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars) } }); }
错误写法1
//错误 => 本质是 get set会一直创建新对象 public static SqlSugarScope Db=> new ...(); //错误 不能get set public static SqlSugarScope Db{get{ retun new xxx}} //错误 不能是方法,调一次方法会创建一次 public static SqlSugarScope Db(){ return new xxx} //错误 SqlSugarClient不能单例只能用 SqlSugarScope public static SqlSugarClient Db=new ...(); //正确写法 public static SqlSugarScope = new ...();
错误写法2:不能在泛型类中new
public class DbContext<T> //错误原因:DbContext<T>.Db 随着T不同他的实例也会不同 { public static SqlSugarScope Db=new ...(); //应该提取到非泛型类或者IOC单例注入 } //正确用法 public class DbContext<T> { public static SqlSugarScope Db = SqlSugarHelper.Db; //在建一个类 }
错误写法3:不能在构造函数内部new
public class DbContext { public DbContext() { Db=new SqlSugarScope..(); //new一次DbContext会创建一个实例 } public static SqlSugarScope Db ; } //正确用法 public static SqlSugarScope Db=mew xxxx();
public class TestManager : DbContext { public List<Order> Add() { return Db.Queryable<Order>().ToList(); } } public class DbContext //如果是泛型类 Db要扔到外面 ,DbContext<T>.Db会导致产生多个实例 { protected static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig() { DbType = SqlSugar.DbType.SqlServer, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true }, db => { //单例参数配置,所有上下文生效 db.Aop.OnLogExecuting = (s, p) => { Console.WriteLine(s); }; }); }
public class TestManager { public List<Order> Add() { return DbContext.Db.Queryable<Order>().ToList(); } } public class DbContext //如果是泛型类 Db要扔到外面 ,DbContext<T>.Db会导致产生多个实例 { //这里要public public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig() { DbType = SqlSugar.DbType.SqlServer, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true }, db => { //单例参数配置,所有上下文生效 db.Aop.OnLogExecuting = (s, p) => { Console.WriteLine(s); }; }); }
SqlSugarScope 内部机质在同一个上下文 是Scope模式,也就是同一个上下文中 真实的SqlSugar对象是同一个,在不同上下文会自动New出不同的对象,而不需要人工处理
解决了单例模式的死锁问题
解决了非单例模式的线程安全问题
解决了 跨方法事务(需要单例或 new sqlsugarscope( 参数单例) )
2016 © donet5.comApache Licence 2.0