c# - 在 .Net Core 中基于每个用户使用不同的连接字符串初始化 DBConext
问题描述
我需要能够根据登录的用户创建具有特定数据库连接字符串的 DBContext。
用户通过 JWT 令牌登录,此时应用程序调用第 3 方以确定他们应该连接到哪个数据库。
我目前正在启动时注册我的 ApplicationDBContext:
services.AddDbContextFactory<ApplicationDBContext>(options => options.UseSqlServer(
Configuration.GetConnectionString("TestDbConString"),
h => h.UseHierarchyId()
));
我也有这个服务:
services.
...
.onAuthenticated(async c => {
await getConnectionData(); // Returns the connection string. This can take a few seconds the first time subsequently it returns cached data.
})
显然我需要稍微改变一下。您将如何使用正确/自定义的连接字符串注册 ApplicationDBContext?
更新:
这是我设置 DbContextFactory 的糟糕尝试。
using Microsoft.EntityFrameworkCore;
using MyApp.Models;
namespace MyApp.Data
{
public class ApplicationDbContextFactory : IDbContextFactory<AppDbContext>
{
public ApplicationDbContextFactory test(){
return new ApplicationDbContextFactory();
}
public AppDbContext CreateDbContext()
{
string ConnectionString = "";
//Magic here to get my ConnectionString.
DbContextOptionsBuilder<AppDbContext> options = new DbContextOptionsBuilder<AppDbContext>();
options.UseSqlServer(
ConnectionString,
h => h.UseHierarchyId()
);
return new AppDbContext(options.Options);
}
}
}
启动,cs
services.AddTransient<ApplicationDbContextFactory>();
services.AddTransient(provider => provider.GetService<ApplicationDbContextFactory>()!.CreateDbContext());
我现在收到一个错误:
Unexpected Execution Error : No service for type 'Microsoft.EntityFrameworkCore.IDbContextFactory`1[MyApp.Data.AppDbContext]' has been registered.
更新 #2 这修复了它:
启动.cs
services.AddTransient<IDbContextFactory<AppDbContext>, ApplicationDbContextFactory>();