在ASP.NET Core 5.0中,您可以使用以下步骤加载/在多个DbContext之间切换:
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("CustomerConnection")));
services.AddScoped();
services.AddScoped();
public class CustomerService : ICustomerService
{
private readonly ICustomerDbContext _dbContext;
public CustomerService(ICustomerDbContext dbContext)
{
_dbContext = dbContext;
}
public IEnumerable GetCustomers()
{
return _dbContext.Customers.ToList();
}
}
using (var scope = serviceProvider.CreateScope())
{
var customerDbContext = scope.ServiceProvider.GetRequiredService();
var appDbContext = scope.ServiceProvider.GetRequiredService();
// 使用需要的DbContext
var customers = appDbContext.Customers.ToList();
var orders = customerDbContext.Orders.ToList();
}
这就是在ASP.NET Core 5.0中加载/在多个DbContext之间切换的基本步骤。通过使用依赖注入和服务提供程序,您可以轻松地管理多个DbContext。