在.net framework迁移到.net core的过程中,由于大量代码都是类似于 xxxRepo = new xxxRepo(),且在多线程中会造成连接丢失,所以暂定的修改方法为每次都直接UseSqlServer
public class BaseXXXContext: XXXContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{envName}.json", optional: false)
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("XXXContext"));
}
}
}
原文链接:.net core 直接实例化新的数据库链接,转载请注明来源!