在 .NET 5 中注入多个数据库连接 SqlSugar 可以使用以下步骤:

  1. 在 Startup.cs 中添加 SqlSugar 的配置,例如:
services.AddScoped<SqlSugarClient>(provider =>
{
    var connectionString = Configuration.GetConnectionString('DefaultConnection');
    var db = new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
    return db;
});
  1. 添加多个数据库连接的配置,例如:
services.AddScoped<SqlSugarClient>(provider =>
{
    var connectionString = Configuration.GetConnectionString('Connection1');
    var db = new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
    return db;
});

services.AddScoped<SqlSugarClient>(provider =>
{
    var connectionString = Configuration.GetConnectionString('Connection2');
    var db = new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
    return db;
});
  1. 在需要使用的地方使用注入的 SqlSugarClient,例如:
public class MyService
{
    private readonly SqlSugarClient _db1;
    private readonly SqlSugarClient _db2;

    public MyService(SqlSugarClient db1, SqlSugarClient db2)
    {
        _db1 = db1;
        _db2 = db2;
    }

    public void DoSomething()
    {
        // 使用 db1 连接的 SqlSugar
        var db1Result = _db1.Queryable<MyEntity>().ToList();

        // 使用 db2 连接的 SqlSugar
        var db2Result = _db2.Queryable<MyEntity>().ToList();
    }
}

注意:不同的 SqlSugarClient 需要使用不同的变量名或者类型来区分。在以上的例子中,使用了 _db1 和 _db2 来区分两个不同的 SqlSugarClient。

.NET 5 多数据库连接注入 SqlSugar 教程

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

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