简体   繁体   English

通过DI将选定的数据库传递给DBcontext

[英]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. 此列表是从一个Admin数据库填充的。 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. 使用“状态”下拉菜单中的DI,我没有任何问题。 However, I am having issues with getting the selected state. 但是,我在获取选定状态时遇到问题。 I tested hardcoding a state and DI works fine. 我测试了状态的硬编码,并且DI可以正常工作。 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. 我想为此使用Session,但是坦白地说,我读过你无法理解,我无法使其工作。 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>();

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. 但是请注意,默认情况下未注册IHttpContextAccessor You can fix that by adding the following in ConfigureServices : 您可以通过在ConfigureServices添加以下内容来解决此问题:

services.AddHttpContextAccessor();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM