优点:.net core 自带用起来比较方便,缺点像winform等就不太方便使用
.NET自带的IOC使用也很方便
注意:
SqlSugarScope用单例AddSingleton 单例
SqlSugarClient用 AddScoped 每次请求一个实例
2选1只能用一种方式
//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
services.AddHttpContextAccessor();
//注册SqlSugar
services.AddSingleton<ISqlSugarClient>(s =>
{
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
DbType = SqlSugar.DbType.Sqlite,
ConnectionString = "DataSource=sqlsugar-dev.db",
IsAutoCloseConnection = true,
},
db =>
{
//单例参数配置,所有上下文生效
db.Aop.OnLogExecuting = (sql, pars) =>
{
//获取作IOC作用域对象
var appServive = s.GetService<IHttpContextAccessor>();
var obj = appServive?.HttpContext?.RequestServices.GetService<Log>();
Console.WriteLine("AOP" + obj.GetHashCode());
};
});
return sqlSugar;
});
//注入仓储具体用法文档 仓储有介绍
//builder.Services.AddScoped(typeof(Repository<>));注入我们都是用的 ISqlSugarClient,ISqlSugarClient 只有单库的所有操作并没租户功能, 原因如下:
SqlSugarClient : ISqlSugarClient, ITenant SqlSugarScope : ISqlSugarClient, ITenant
所以我ISqlSugarClient缺失了租户接口的方法,我们如果要用租户方法代码如下:
/// <summary>
///
/// </summary>
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
ISqlSugarClient db;
public WeatherForecastController(ISqlSugarClient db)
{
this.db = db;//通过构造函数拿到注入的db
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IEnumerable<WeatherForecast>> GetAsync()
{
//如果要使用租户下面的方法 按下面转一下就可以用了
//db.AsTenant().BeginTran();
//db.AsTenant().GetConnection("db1")
//老版本 (db as ITenant).BeginTran()
//如果你直接转换也可以 db as SqlSugarClient , db as SqlSugarScope
//使用db查询
var list = await db.Queryable<WeatherForecast>().ToListAsync();
return list;
}
}https://www.donet5.com/Doc/27/2563
优点:适合自带的IOC不能用的情况下使用,比如WinFrom等会比较方便
安装: SqlSugar.Ioc & SqlSugarCore
.NET Core 3.0+ .NET 5- .NET 9
// 10秒入门
SugarIocServices.AddSqlSugar(new IocConfig()
{
//ConfigId="db01" 多租户用到
ConnectionString = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST",
DbType = IocDbType.SqlServer,
IsAutoCloseConnection = true//自动释放
}); //多个库就传List<IocConfig>
//配置参数
SugarIocServices.ConfigurationSugar(db =>
{
db.Aop.OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
};
//设置更多连接参数
//db.CurrentConnectionConfig.XXXX=XXXX
//db.CurrentConnectionConfig.MoreSettings=new ConnMoreSettings(){}
//二级缓存设置
//db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
//{
// DataInfoCacheService = myCache //配置我们创建的缓存类
//}
//读写分离设置
//laveConnectionConfigs = new List<SlaveConnectionConfig>(){...}
/*多租户注意*/
//单库是db.CurrentConnectionConfig
//多租户需要db.GetConnection(configId).CurrentConnectionConfig
});
//CodeFirst请写这儿,与SugarIocServices.AddSqlSugar平级
//DbScoped.SugarScope.CodeFirst<T>();
//注入后就能所有地方使用
DbScoped.SugarScope.Queryable<UserOrgMapping>().Where(it=>it.Id>0).ToList() //1.7版本支持
DbScoped.Sugar.Queryable<UserOrgMapping>().Where(it=>it.Id>0).ToList()
//DbScoped.SugarScope=SqlSugarScope (推荐)
//DbScoped.Sugar=SqlSugarClient详细文档入口:SqlSugar.IOC使用--文档园 (donet5.com)
2016 © donet5.comApache Licence 2.0