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
  • 2,926
  • 4
  • 30
  • 70

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
  • 12,749
  • 5
  • 51
  • 68