【发布时间】:2016-01-03 15:55:26
【问题描述】:
我正在开发多租户应用程序。我为每个租户使用单独的数据库。 UserData 也适用于单独数据库中的每个租户。
我的问题是如何在 DI 上独立地为“自定义”数据库中的每个租户创建管理员帐户。在 MVC 5 中,可以基于 UserStore(连接字符串)实例化 UserManager。但是 mvc6 中的 UserManager 依赖于 HttpContext...没有找到文档... 存在请某种方式怎么做???我在 mvc 6 中需要类似 mvc 5 的东西:
UserStore<TenantUser> store = new UserStore<TenantUser>(new TenantDbContext("CONNECTION STRING")); //!!! NO POSSIBLE CREATE USER IN CUSTOM DATABASE
UserManager<TenantUser> t = new UserManager<TenantUser>(store);
t.CreateAsync(user, password);
更新:
public class TenantDbContext : IdentityDbContext<TenantUser, TenantRole, Guid>
{
private string _connectionString { get; set; }
private readonly IHttpContextAccessor _contextAccessor;
private readonly ApplicationDbContext _applicationDbContext;
//THIS SUB UNCOMENT ONLY IF CREATE MIGRATIONS (dnx ef...)
/*
public TenantDbContext(DbContextOptions<TenantDbContext> options) : base(options)
{
this._connectionString = "CONNECTION STRING";
}
*/
public TenantDbContext(DbContextOptions<TenantDbContext> options, IHttpContextAccessor contextAccessor, ApplicationDbContext applicationDbContext) : base(options) {
_contextAccessor = contextAccessor;
_applicationDbContext = applicationDbContext;
TenantResolver resolver = new TenantResolver(_contextAccessor, _applicationDbContext);
string con = resolver.GetConnectionString();
if (con != string.Empty)
{
this._connectionString = con; }
else
{
this._connectionString = "CONNECTION STRING"; //Development connection string
}
}
public TenantDbContext() //Posibility to create TenantDbContext migration and development database with no connectionString in constructor
{
//this._connectionString = "CONNECTION STRING";
}
public TenantDbContext(string ConnectionString)
{
this._connectionString = ConnectionString;
}
public static TenantDbContext Create(string ConnectionString)
{
return new TenantDbContext(ConnectionString);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
【问题讨论】:
-
有很多方法可以解决您的问题。 需要了解更多信息。 您是否在
appsettings.json中定义了您需要的两个连接字符串?您是如何创建TenantDbContext(手动,使用dnx ef dbcontext scaffold)的?你有两个上下文(TenantDbContext1和TenantDbContext2)。在 ASP.NET 5 中使用的一种通常是依赖注入。它允许在Startup.cs的ConfigureServices中注册所有必需的上下文,new DbContext将被服务调用并转发给 Controller 的构造函数或控制器的每个 Action。 -
我创建了两个 DbContext:ApplicationDbContext 和 TenantDbContext。 ApplicationDbContext 用于所有共享数据。TenantDbContext 取决于子域(ConectionString 基于子域解析)。对于 DbContexts 使用 DI...问题是如何在新数据库中创建用户...我无法在启动服务中注册 TenantDbContext。它取决于连接字符串(许多租户......)
-
您能否发布更多代码片段,它准确地说明了您所做的事情。如果您写“许多租户”,您的意思是什么。你有一些特定的上下文列表吗?您在哪种情况下知道详细信息(连接字符串)?例如,我可以向您展示如何动态更改 one 上下文的
ConnectionString,但可能需要关闭现有连接并重新打开另一个连接。 -
请查看更新.. 许多租户 = 一个具有多个连接字符串的 TenantDbContext 类。连接字符串是在运行时从数据库中加载的......请参阅 TenantResolver 解析器......
-
我要离开几个小时,所以我刚刚发布了我的答案。
标签: asp.net-mvc asp.net-identity asp.net-core-mvc asp.net-core