首页 > 解决方案 > 如何在运行时添加 DbContext

问题描述

我正在尝试DbContext在运行时添加一个。我这样做的原因是因为客户端使用不同的数据库模式。通过这样做,我无法将它添加到 的ConfigureServices方法中,StartUp因为我需要先了解客户端,然后尝试在其中创建具有适当模式的连接字符串,因为Configure每次发出请求时都会调用该方法。我已经尝试访问,IServiceCollection但容器说没有IServiceCollection注册类型的服务。我现在尝试在 startUp 的ConfigureServices方法中注册 IServiceCollection 本身,然后应用程序拒绝完全启动。有没有更好的方法在运行时添加它?

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceCollection services)
        {
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());


            app.UseAuthentication();
            app.UseMvc();

            IClientValidator clientValidator = app.ApplicationServices.GetRequiredService<IClientValidator>();
            services.AddDbContext<ClientDbContext>(options =>
                options.UseSqlServer(clientValidator.GetConnectionString()));
        }

客户端验证器负责解析客户端连接字符串。

标签: c#asp.net-coreasp.net-core-webapi

解决方案


QueryTrackingBehaviour.NoTracking好的,我通过添加重载解决了重新初始化问题AddDbContext

services.AddDbContext<DatabaseContext>(options =>
{
    options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    options.UseSqlServer(databaseSettings.DefaultConnection);
});

底线是,我没有在启动文件中执行此操作,而是通过覆盖但我在上面讨论的方法之前找到了更好的解决方案来OnConfiguring初始化连接。DbContext解决方案如下

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connectionString).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
}

推荐阅读