SqlSugar 使用 IOC 有 2 种方式 ,2 种方式不能混用,用一种就可以了
SqlSugar.IOC
SqlSugar.IOC 用法简单,注入直接开箱就用
Nuget 安装 SqlSugar.Ioc 和 SqlSugarCore
.NET Core 3.0 + .NET 5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| SugarIocServices.AddSqlSugar(new IocConfig() { ConnectionString = "server=.;uid=sa;pwd=123456;database=SQLSugarDemo", DbType = IocDbType.SqlServer, IsAutoCloseConnection = true });
SugarIocServices.ConfigurationSugar(db => { db.Aop.OnLogExecuting = (sql, p) => { Console.WriteLine(sql); };
});
DbScoped.SugarScope.Queryable<UserOrgMapping>().Where(it=>it.Id>0).ToList() DbScoped.Sugar.Queryable<UserOrgMapping>().Where(it=>it.Id>0).ToList()
|
.NET IOC
注入 ISqlSugarClient
.NET 自带的 IOC 使用也很方便
注意:
SqlSugarScope 用单例 AddSingleton 单例
SqlSugarClient 用 AddScoped 每次请求一个实例
2 选 1 只能用一种方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration) { var str = configuration.GetConnectionString("SqlServer");
SqlSugarScope sqlSugar = new(new ConnectionConfig() { ConnectionString = str, DbType = DbType.SqlServer, IsAutoCloseConnection = true, }, db => { db.Aop.OnLogExecuting = (sql, pars) => { }; });
sqlSugar.DbMaintenance.CreateDatabase(); sqlSugar.CodeFirst.InitTables(typeof(Users));
services.AddSingleton<ISqlSugarClient>(sqlSugar); }
|
在 Startup 文件添加下面代码
1
| services.AddSqlsugarSetup(Configuration);
|