Typically DbContext
and ConnectionString are set at application start. In my ASP.NET MVC application I have a database with Users and ConnectionStrings data and depending on which user logs in, I want to use their ConnectionString to connect them to a secondary DbContext.
I tried to use DbContextScope but with the current implementation it doesn't seem to support this scenario. (I posted a related question for that here).
So in lifecycle of an ASP.NET MVC application how can we make sure the secondary DbContext is instantiated only after the user is logged in? What's the correct way to manage the lifecycle of DbContext here.
Thanks!
There is an overload for DbContext that takes in the connection string. With this, you could add a constructor to pass in the secondary connection string based upon the user that is accessing data.
Alternatively, you could pass in a user object that has the connection string to use.
Hope this helps you out.
Update for Lifecycle
As to the lifecycle, you could use something like this with a null check from the calling side.
This will prevent the secondary DbContext from being instantiated prior to the user being logged in.