Passing a selected database to a DBcontext via DI

asp.net-core-2.0 entity-framework-core

Question

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 =>
            options.UseSqlServer(Configuration.GetSection("Connections:myAdmin").Value).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));          

        //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?
            //HttpContext.Session.GetString("SelectedState");

            //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);
            builder.UseSqlServer(connectionString);
        });

        //my one admin database Data context
        services.AddScoped<AdminManagement.Data.AdminManagementQueries>();

        // my multiple databases clases that use DI
        services.AddScoped<CollectionManagementQueries>();
        services.AddScoped<CollectionManagementCommands>();
1
0
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:

services.AddHttpContextAccessor();
1
8/29/2018 1:28:14 PM


Related Questions





Related

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