Asume我有4台服务器和4个dbs,它们都有相同的目录。是否可以在运行时更改{serverLocation}?
"ConnectionStrings": {
"Euro": "Data Source=campus-db-{serverLocation};Initial Catalog=Shool;Integrated Security=True"}
方法应该看起来像这样:
[HttpGet]
public async Task<IActionResult> GetStock(int id, string serverLocation)
{
var queryStock = _context.TblItem.FindAsync(id);
return Ok(queryStock);
}
这个想法是,我只需要1个DBContext 1 Model,因为在所有4台服务器上,目录都是相同的,数据库结构是
你可以这样写,但我不确定
IConfiguration _configuration;
public StockManager(IConfiguration configuration)
{
_configuration = configuration;
}
public object FindAsync(int id,serverLocation)
{
//do stuff
_configuration.GetConnectionString($"ConnectionStrings:{serverLocation}");
}
这可能会对您有所帮助,请检查。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<ApplicationDbContext>(
options =>
{
var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
var httpRequest = httpContext.Request;
// Now you can get access to the http context here, do what ever you want to do here with httpRequest.
// write conditional statements here like
if(somecondition-a)
options.UseSqlServer("name=ConnectionStrings:Connection-A"));
if(somecondition-b)
options.UseSqlServer("name=ConnectionStrings:Connection-B"));
}
}
有关更多信息,请查看此文档
如果这没有帮助,尝试这种方法
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextFactory<ApplicationDbContext>(
options =>
{
var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
var httpRequest = httpContext.Request;
// Now you can get access to the http context here, do what ever you want to do here with httpRequest.
// write conditional statements here like
if(somecondition-a)
options.UseSqlServer("name=ConnectionStrings:Connection-A"));
if(somecondition-b)
options.UseSqlServer("name=ConnectionStrings:Connection-B"));
}
}