【问题标题】:Passing a selected database to a DBcontext via DI通过 DI 将选定的数据库传递给 DBcontext
【发布时间】:2019-02-04 06:07:13
【问题描述】:

这是我的场景。想象一个带有美国各州下拉列表的屏幕。此列表由一个管理员数据库填充。根据屏幕上其他项目的选择,会填满其他数据库。我们每个州都有一个共享单个模式的数据库。将 DI 用于美国下拉菜单没有任何问题。但是,我在获取选定状态时遇到问题。我测试了对状态的硬编码,DI 工作正常。我想为此使用 Session,但我读过你不能,坦率地说,我无法让它工作。任何建议,将不胜感激。

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

【问题讨论】:

    标签: entity-framework-core asp.net-core-2.0


    【解决方案1】:

    您需要从服务提供者那里检索上下文。这是通过:

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

    然后,您可以执行以下操作:

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

    但是请注意,IHttpContextAccessor 默认情况下未注册。您可以通过在ConfigureServices 中添加以下内容来解决此问题:

    services.AddHttpContextAccessor();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 2021-12-02
      • 2015-11-11
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      相关资源
      最近更新 更多