joseluisrod
joseluisrod

Reputation: 82

Passing a selected database to a DBcontext via DI

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>();

Upvotes: 0

Views: 36

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239420

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();

Upvotes: 1

Related Questions