Skip to content

MultipleDatabase

shuxin edited this page Mar 24, 2023 · 5 revisions

连接多库

1. 建立不同的上下文接口

public interface IDbContextA : IDbContext
{

}
public interface IDbContextB : IDbContext
{

}

public class DbContextA : MsSqlContext, IDbContextA
{
    public DbContextA(string connString) : base(connString)
    {

    }
}
public class DbContextB : MsSqlContext, IDbContextB
{
    public DbContextB(string connString) : base(connString)
    {

    }
}

2. 注入 IOC

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddDatabase(this IServiceCollection services)
    {
        services.AddScoped<IDbContextA>(a =>
        {
            return new DbContextA("connection string A");
        });

        services.AddScoped<IDbContextB>(a =>
        {
            return new DbContextB("connection string B");
        });

        services.AddScoped<YourRepository>();

        return services;
    }
}

3. 使用

public class YourRepository
{
    IDbContext _dbContextA;
    IDbContext _dbContextB;
    public YourRepository(IDbContextA dbContextA, IDbContextB dbContextB)
    {
        this._dbContextA = dbContextA;
        this._dbContextB = dbContextB;
    }
}