每个租户的数据库 - 一步一步的例子来证实我的想法 [英] Database per tenant - a step by step example to confirm my thinking

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

问题描述

我只需要确认我在尝试实施的这方面走在正确的轨道上.

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 eg

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天全站免登陆