可以使用命名空间来区分不同的SqlSugarClient,例如:

services.AddScoped<SqlSugarClient>("Client1", provider =>
{
    return new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = "connection string 1",
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
});

services.AddScoped<SqlSugarClient>("Client2", provider =>
{
    return new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = "connection string 2",
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
});

在需要使用SqlSugarClient的地方,可以通过指定命名空间来获取对应的SqlSugarClient:

private readonly SqlSugarClient _client1;
private readonly SqlSugarClient _client2;

public MyClass(IServiceProvider serviceProvider)
{
    _client1 = serviceProvider.GetRequiredService<SqlSugarClient>("Client1");
    _client2 = serviceProvider.GetRequiredService<SqlSugarClient>("Client2");
}
``
net5中如何通过AddScoped分别注入两个SqlSugarClient使用无法命名

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

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