Passing a selected database to a DBcontext via DI

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

Question

This is how I see it. Consider a screen that has a dropdown menu of US states. One Admin database is used to fill up this list. Various things on the screen populate with other databases based on the selections made by the user. Each state has its own database that is shared by all of them. I have no objections about utilizing DI in the States option. I am having trouble acquiring the chosen state, however. Hardcoding a state worked as intended when I tried it. 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 advice would be much 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

ZZZ_tmp
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