net5中如何通过AddScoped分别注入两个SqlSugarClient使用无法使用命名空间的方式
可以使用自定义的工厂方法来分别注入两个SqlSugarClient。
首先,创建一个自定义的工厂类:
public class SqlSugarClientFactory
{
private readonly IConfiguration _configuration;
public SqlSugarClientFactory(IConfiguration configuration)
{
_configuration = configuration;
}
public SqlSugarClient CreateClient1()
{
var connection = _configuration.GetConnectionString("Connection1");
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = connection,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
public SqlSugarClient CreateClient2()
{
var connection = _configuration.GetConnectionString("Connection2");
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = connection,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
}
在Startup.cs中进行注册:
services.AddScoped<SqlSugarClientFactory>();
services.AddScoped<SqlSugarClient>(serviceProvider =>
{
var factory = serviceProvider.GetService<SqlSugarClientFactory>();
return factory.CreateClient1();
});
services.AddScoped<SqlSugarClient>(serviceProvider =>
{
var factory = serviceProvider.GetService<SqlSugarClientFactory>();
return factory.CreateClient2();
});
在需要使用SqlSugarClient的类中,可以使用构造函数注入方式进行注入:
public class MyClass
{
private readonly SqlSugarClient _client1;
private readonly SqlSugarClient _client2;
public MyClass(SqlSugarClient client1, SqlSugarClient client2)
{
_client1 = client1;
_client2 = client2;
}
public void Method1()
{
// 使用_client1操作数据库
}
public void Method2()
{
// 使用_client2操作数据库
}
}
``
原文地址: https://www.cveoy.top/t/topic/hhKj 著作权归作者所有。请勿转载和采集!