每个租户的数据库-逐步确认我的想法的示例 [英] Database per tenant - a step by step example to confirm my thinking

查看:112
本文介绍了每个租户的数据库-逐步确认我的想法的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要确认我在尝试实现的这一方面处于正确的轨道即可.

I just need confirmation I'm on the right track with this aspect I'm trying to implement.

第1步:为每个租户创建一个新的上下文,例如

Step 1: for each tenant create a new context eg

public class TenantOneContext : AbpZeroDbContext<Tenant, Role, User, TenantOneContext{


  public DbSet<MyModel1> MyModel1S { get; set; }
  public DbSet<MyModel1> MyModel2S { get; set; }

第2步: 我假设使用命名约定,即每个存在的上下文都有一个关联的[contextname] Configurer例如

Step 2: I assume using a naming convention, that each context that exists, there is an associated [contextname]Configurer eg

public static class TenantOneContextConfigurer
    {
        public static void Configure(DbContextOptionsBuilder<TenantOneContext> builder, string connectionString)
        {
            builder.UseSqlServer(connectionString);
        }

        public static void Configure(DbContextOptionsBuilder<TenantOneContext> builder, DbConnection connection)
        {
            builder.UseSqlServer(connection);
        }

步骤3 :为每个租户上下文创建新的[contextname] Factory,例如

Step 3: create new [contextname]Factory for each tenant-context eg

 public class TenantOneContextFactory : IDesignTimeDbContextFactory<TenantOneContext>

在继承AbpModule的模块中-添加一些代码以进行自定义连接字符串解析,例如

In the module that inherits AbpModule - add some code to do custom connection string resolving eg

public class MyAppEntityFrameworkModule : AbpModule { 

  //new code to  resolve conn strings / tennant
   Configuration.ReplaceService<IConnectionStringResolver, DbPerTenantConnectionStringResolver>(DependencyLifeStyle.Transient);

我认为就是这样-但是正在寻找确认...:-)

I think that is it - but looking for confirmation...:-)

推荐答案

您可能不需要为每个租户使用不同的DbContext,而只需使用不同的连接即可.

You probably don't need a different DbContext for each tenant, just a different connection.

如果是这样,是否存在用于映射conn字符串的命名约定?或在哪里进行映射?

if so, is there a naming convention for mapping the conn strings ? or where does the mapping take place?

连接字符串存储在

The connection string is stored in Tenant entity:

public const int MaxConnectionStringLength = 1024;

[StringLength(MaxConnectionStringLength)]
public virtual string ConnectionString { get; set; }

映射发生在 DbPerTenantConnectionStringResolver :

if (args.TenantId == null)
{
    // Requested for host
    return base.GetNameOrConnectionString(args);
}

var tenantCacheItem = _tenantCache.Get(args.TenantId.Value);
if (tenantCacheItem.ConnectionString.IsNullOrEmpty())
{
    // Tenant has no dedicated database
    return base.GetNameOrConnectionString(args);
}

return tenantCacheItem.ConnectionString;

这篇关于每个租户的数据库-逐步确认我的想法的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆