0

I have .NET Core app with dynamic DB, that I get from http request (subdomain). And I do the following in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddDbContext<AppDbContext>((serviceProvider, options) =>
    {
        var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
        //todo get subdomain
                
        options.UseSqlServer(Configuration.GetConnectionString("DataContext").Replace(":dbname", dbName));
    });
    ...
}

But httpContext variable is null. Why is it null and how can I resolve it?

I looked at this link Dynamically change connection string in Asp.Net Core but it seems nothing works from there

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82

1 Answers1

1

An HttpContext only exists when there is a request, that's why you won't get any outside of one.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74