I have facing a problem to connecting to DBcontext with multiple connection. please help me out from this problem , here is me scenario .
I have an Angular5 application and Webapi Controllers. I have 4 databases and Each database has different users .
When 4 user are trying to connecting to their database at Same time through Webapi controller , that time all users are getting data from single database (instead of getting different database ) .
When we try to Connecting one by one then data getting correctly .
Here is my sample code for dynamic connection .
Context Connectionstring :
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(LoginController.ConnectionString);
}
Controler API :
public IEnumerable<object> Getvendordetails([FromBody] dynamic id)
{
if (Request != null)
{
LoginController.DynamicDbname = Request.Headers["Connectionstring"];
}
ContextEntity obj = new ContextEntity();
}
Here LoginController.DynamicDbname is Static variable .
EDIT CODE :
Controller :
namespace AngularDotnetCore.Controllers
{
[Route("api/[controller]")]
public class HomeController : Controller
{
private readonly IHttpContextAccessor httpContext;
private ContextEntity db;
public HomeController(IHttpContextAccessor _httpContext)
{
this.httpContext = _httpContext;
db = new ContextEntity(httpContext);
}
[HttpPost("GetVendors")]
public IEnumerable<object> Getvendordetails([FromBody] dynamic id)
{
//string DynamicConnection = Request.Headers["Connection"];
db = new ContextEntity(httpContext);
return db.Vendors;
}
[HttpGet("GetItems")]
public IEnumerable<object> GetItems()
{
//string DynamicConnection = Request.Headers["Connection"];
db = new ContextEntity(httpContext);
return db.Items;
}
}
}
DBContext :
private readonly HttpContext httpContext;
public ContextEntity(IHttpContextAccessor httpContextAccessor)
: base()
{
httpContext = httpContextAccessor.HttpContext;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = httpContext.Request.Headers["Connection"];
optionsBuilder.UseSqlServer(connection);
}
I have pass httpcontext parameter to Dbcontext base class for each API Request.
Please help me on this problem , if my code is wrong please suggest me in good way.
Thanks Victor.A