ASP.NET Core在启动过程中使用数据库实例的几种方式
ASP.NET Core项目启动过程中若要调用SqlSugarClient实例操作数据库数据(假设操作函数如下),特此记录以下几种方式:
public class PublicDataBuffer
{
public static List<EnvironmentRecord> DataBuffer = new List<EnvironmentRecord>();
public static void InitDataBuffer(ISqlSugarClient dbClient)
{
DataBuffer.AddRange(dbClient.Queryable<EnvironmentRecord>().Select(r => new EnvironmentRecord()).ToPageList(1, 100).ToList());
}
}
1)如果是在SqlSugar数据库实例首次创建时调用操作函数,则在Program.cs文件的注册数据库服务的代码中调用即可。此时操作函数并未直接在启动过程中调用,而是在项目第一次操作数据库时调用。
builder.Services.AddSingleton<ISqlSugarClient>(s =>
{
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = builder.Configuration.GetValue<string>("dbContext"),
IsAutoCloseConnection = false,
});
PublicDataBuffer.InitDataBuffer(sqlSugar);
return sqlSugar;
});
2)直接在Program.cs中创建数据库实例,既用于注册单例服务,又用于操作函数调用。
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = builder.Configuration.GetValue<string>("dbContext"),
IsAutoCloseConnection = false,
});
uilder.Services.AddSingleton<ISqlSugarClient>(sqlSugar);
PublicDataBuffer.InitDataBuffer(sqlSugar);
3)Program.cs中调用WebApplication的Services.GetService函数获取服务实例。
...
...
var app = builder.Build();
...
PublicDataBuffer.InitDataBuffer(app.Services.GetService<ISqlSugarClient>());
...
...
参考文献:
[1]https://blog.csdn.net/fromfire2/article/details/87348154
[2]https://blog.csdn.net/qq_41942413/article/details/134319869
[3]https://cloud.tencent.com/developer/article/2347045
原文地址:https://blog.csdn.net/gc_2299/article/details/140569063
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!