.NET 5 中使用 AddScoped 注入多个 SqlSugarClient 实例
在 .NET 5 中,可以使用 AddScoped 方法注入多个 SqlSugarClient 实例,从而连接到不同的数据库。以下示例展示如何使用 AddScoped 注入两个 SqlSugarClient 实例:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<SqlSugarClient>(provider =>
{
var options = new ConnectionConfig
{
ConnectionString = Configuration.GetConnectionString("DefaultConnection"),
DbType = DbType.SqlServer,
IsAutoCloseConnection = true
};
return new SqlSugarClient(options);
});
services.AddScoped<SqlSugarClient>("SecondDb", provider =>
{
var options = new ConnectionConfig
{
ConnectionString = Configuration.GetConnectionString("SecondConnection"),
DbType = DbType.SqlServer,
IsAutoCloseConnection = true
};
return new SqlSugarClient(options);
});
}
在上面的代码中,我们使用 AddScoped 方法分别注册了两个 SqlSugarClient 实例。第一个实例的服务类型为 SqlSugarClient,第二个实例的服务类型为 'SecondDb'。
当需要使用这两个实例时,可以在构造函数中注入它们,例如:
public class MyService
{
private readonly SqlSugarClient _sqlSugarClient;
private readonly SqlSugarClient _secondSqlSugarClient;
public MyService(SqlSugarClient sqlSugarClient, SqlSugarClient secondSqlSugarClient)
{
_sqlSugarClient = sqlSugarClient;
_secondSqlSugarClient = secondSqlSugarClient;
}
// 使用 _sqlSugarClient 和 _secondSqlSugarClient 进行数据库操作
}
在 MyService 类的构造函数中,我们注入了两个 SqlSugarClient 实例,并将它们保存在私有字段中。这样,就可以在 MyService 类中使用这两个实例进行数据库操作。注意,第一个注入的实例的服务类型为 SqlSugarClient,第二个注入的实例的服务类型为 'SecondDb'。在使用时,需要根据服务类型来获取对应的实例。
原文地址: https://www.cveoy.top/t/topic/oKz2 著作权归作者所有。请勿转载和采集!