.NET core DbContext dynamic connectionstring

Viewed 6699

I am trying to set the connectionstring of my DbContext depending on each http request header. Is it possible to do so in .NET Core? I did it in MVC5 but I am not able to implement it in .NET core.

At

public void ConfigureServices(IServiceCollection services)
{
    // ...
}

I don't know the http header, so where can I do it?

2 Answers

This way you can do it even more streamlined

services.AddScoped<ISqlConnectionContext, SqlConnectionContext>();
services.AddDbContext<SqlDbContext>((sp, builder) =>
    builder.UseSqlServer(sp.GetRequiredService<ISqlConnectionContext>().GetConnectionString()));

The SqlConnectionContext can now be implemented in any way you want. For example using the IHttpContextAccessor.

Related