Passing a selected database to a DBcontext via DI entity-framework-core


Here is my scenario. Imagine a screen with a dropdown of US states. This list is populated from one Admin database. Depending on the choice of other items on the screen get filled with other databases. we have a database per state that share a single schema. I don't have any issue using DI for the States dropdown. However, I am having issues with getting the selected state. I tested hardcoding a state and DI works fine. I would like to use Session for this, but I have read you can't and frankly, I have not been able to make it work. Any suggestions would be appreciated.

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped(p => p.GetService<IHttpContextAccessor>()?.HttpContext);

        services.AddDbContext<AdminManagement.Data.AdminDataContext>(options =>

        //this is the issue here I want to be able to pass the selected state 
        services.AddDbContext<CollectionDataContext>((serviceProvider, builder) =>
            //I wish I could use this...any alternatives?

            //hardcoded for testing purposes. it works ok 
            var selectedDb = "SC"; 

            //this gets the connection string from app settings, later I will get it from an API
            var connectionString = GetConnectionStringFromService(selectedDb);

        //my one admin database Data context

        // my multiple databases clases that use DI
8/29/2018 12:41:04 PM

Popular Answer

You need to retrieve the context from the service provider. That's done via:

var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();

Then, you can do something like:

var selectedDb = httpContextAccessor.HttpContext.Session.GetString("SelectedState");

Note, however, that IHttpContextAccessor is not registered by default. You can fix that by adding the following in ConfigureServices:

8/29/2018 1:28:14 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow