可以使用命名注入的方式,在注入时指定不同的名称,如下所示:

services.AddScoped<SqlSugarClient>(provider => new SqlSugarClient(new ConnectionConfig
{
    ConnectionString = Configuration.GetConnectionString('Connection1'),
    DbType = DbType.SqlServer,
    IsAutoCloseConnection = true
}), 'Client1');

services.AddScoped<SqlSugarClient>(provider => new SqlSugarClient(new ConnectionConfig
{
    ConnectionString = Configuration.GetConnectionString('Connection2'),
    DbType = DbType.SqlServer,
    IsAutoCloseConnection = true
}), 'Client2');

然后在需要使用的地方,通过名称来获取已经注入的 SqlSugarClient,如下所示:

public class MyService
{
    private readonly SqlSugarClient _client1;
    private readonly SqlSugarClient _client2;

    public MyService(
        [Named('Client1')] SqlSugarClient client1,
        [Named('Client2')] SqlSugarClient client2)
    {
        _client1 = client1;
        _client2 = client2;
    }

    // ...
}

原文地址: https://www.cveoy.top/t/topic/oKzM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录