The other answer by Tolbxela suggest creating a new context when needed, where needed but that does not work if you want to use dependency injection. Instead, you should provide a factory like this in the ConfigureServices
method of your Startup
class using the AddDbContext
extensions method as Camilo stated in the comment of that answer:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
...
services.AddDbContext<BloggingContext>(options =>
{
var customerId = serviceProvider.GetService<IHttpContextAccessor>().HttpContext?.User?.FindFirst("customerId")?.Value;
var connectionString =
$"bla blah blah ;Initial Catalog={customerId}";
options.UseSqlServer(connectionString);
In this example the initial catalog is set to the value of a claim "customerId". (FindFirst
is a custom extension method I wrote myself). This example is only to give you an idea of the approach.
You can then inject your context like you would normally do:
public class MyController : Controller
{
public MyController(BloggingContext context)
{
...
}
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…