1、安装SqlSugar包,打开程序包管理控制台,输入以下命令(或直接在管理解决方案的Nuget程序包中下载)
Install-Package SqlSugarCore
2、使用扩展方法编写AddSqlClient扩展方法,用于将 SqlSugarClient
注册到 IServiceCollection
中
public static class Services
{
public static IServiceCollection AddSqlClient<T>(this IServiceCollection services,Func<ConnectionConfig>configAction) where T : SqlSugarClient
{
var config = configAction();
services.AddScoped(serviceProvider =>
{
var db = new SqlSugarClient(config);
return (T)db;
});
return services;
}
}
3、在Program.cs中添加以下代码注入SqlSugar服务(必须写在var app = builder.Build()之前),这样就完成了SqlSugar服务的注册
builder.Services.AddSqlClient<SqlSugarClient>(()=>new ConnectionConfig
{
DbType = DbType.SqlServer,
ConnectionString= "Server=.;Database=demo2;User Id=sa;Password=111111;MultipleActiveResultSets=True;Pooling=False;",
IsAutoCloseConnection = true,
});
4、使用SqlSugar服务,我们可以通过构造函数注入来获取它的实例
public class SomeService
{
private readonly SqlSugarClient _db;
public SomeService(SqlSugarClient db)
{
_db = db;
}
public void SomeMethod()
{
// 使用 _db 进行数据库操作
}
}