Multiple connection to DbContext in EFCore and .net Core2.0

杀马特。学长 韩版系。学妹 提交于 2019-12-02 13:25:53

If LoginController.DynamicDbName is a static variable, It is shared between all your requests. It means Your API is overrading this value on each request and all users are using the last one to create dbconnection. Make it non static and create new instance of your login contoller for each request and inject It to all related services like DbContext. Then your problem will disappear.

If you are using migrations from command line, you might need to upgrade EF Core version to 2.1 (or 2.2, I can't remeber) because 2.0 has some problem with injecting not-standard classes/interfaces to your Context

For accessing http header from DbContext, you could try IHttpContextAccessor, there is no need to refer LoginContoller.

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    private readonly HttpContext httpContext;
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
        httpContext = httpContextAccessor.HttpContext;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connection = httpContext.Request.Headers["Connectionstring"];
        optionsBuilder.UseSqlServer(connection);
    }       
}

Edit It seems you initlize the ContextEntity in the controller instead of using DI, if so, try passing the connectionstring directly instead of IHttpContextAccessor.

namespace AngularDotnetCore.Controllers
   {
 [Route("api/[controller]")]
public class HomeController : Controller
{      
   private ContextEntity db;
  public HomeController()
{

    var connection = Request.Headers["Connection"];
    db = new ContextEntity(connection);

}
  }

DbContext

private readonly string _connection;
  public ContextEntity(string connection)
: base()
{
    _connection = connection;
}
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
  optionsBuilder.UseSqlServer(_connection);

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!