c# - 如何在运行时添加 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()));
}
客户端验证器负责解析客户端连接字符串。
解决方案
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));
}
推荐阅读
- swift - 如何根据设备中心在按钮按下的位置将节点添加到 ARKit 场景?
- html - 如何在 Shopify Buy Button 的 iFrame 中实施 CSS 更改
- git - 除非将用户名添加到 url,否则找不到 Git 存储库
- vba - VBA raising events from modeless Userfrom
- r - 使用 for 循环在 R 中使用 manova?
- java - (Java) 从文件中读取时如何跳过空格?
- azure - Azure 部署脚本测试,无需部署资源
- html - 为什么我的页脚不在页面底部?
- node.js - 向现有 AWS CloudFormation 堆栈添加新的输出和资源
- python - 在字典中搜索单词并返回行