max*_*ntz 6 c# asp.net-web-api entity-framework-core asp.net-core
我正在使用ASP.NET5的Web API和EF7构建后端服务来设置多租户数据库结构.要求如下:
我现在面临以下挑战:
为了使服务能够动态添加或删除租户,我当前的实现基于JSON配置文件,该文件包含键值对中的所有租户连接字符串,如下所示:
{
"Tenants": [
{ "Tenant1": "Server=.\\SQLEXPRESS;Database=Tenant1;integrated security=True;" },
{ "Tenant2": "Server=.\\SQLEXPRESS;Database=Tenant2;integrated security=True;" }
]
}
Run Code Online (Sandbox Code Playgroud)
然后使用此配置来设置ContextFactory.此工厂使用DbContextOptions存储,以便在需要时动态创建DbContext实例,从而实现必要的短生命周期.工厂定义如下:
public class TenantContextFactory : ITenantContextFactory
{
/// <summary>
/// The tenant configurations store.
/// </summary>
private IDictionary<string, DbContextOptions> tenants;
/// <summary>
/// Creates a new TenantContextFactory
/// </summary>
public TenantContextFactory()
{
tenants = new Dictionary<string, DbContextOptions>();
}
/// <summary>
/// Registers a tenant configuration with the store.
/// </summary>
/// <param name="id">The tenant id.</param>
/// <param name="options">The context options.</param>
public void RegisterTenant(string id, DbContextOptions options)
{
if (!tenants.ContainsKey(id))
{
tenants.Add(id, options);
}
}
/// <summary>
/// Creates a DbContext instance for the specified tenant.
/// </summary>
/// <typeparam name="T">The type of DbContext to create.</typeparam>
/// <param name="id">The tenant id.</param>
/// <returns>A new instance of the desired DbContext</returns>
public T GetTenantContext<T>(string id) where T : DbContext
{
DbContextOptions options;
if (tenants.TryGetValue(id, out options))
{
// get the type of the desired DbContext and return a new instance
// with the DbContextOptions as the constructor parameter
return (T)Activator.CreateInstance(typeof(T), options);
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
在配置阶段,ContextFactory使用扩展方法填充租户信息,如下所示:
public static class ExtensionMethods
{
/// <summary>
/// Adds multi tenancy to the service.
/// </summary>
/// <param name="services">The service collection</param>
/// <param name="config">The configuration object</param>
public static void AddMultiTenancy(this IServiceCollection services, IConfiguration config)
{
var tenantContextFactory = new TenantContextFactory();
// get the information from the JSON file
var tenants = config.GetSection("Tenants");
var values = tenants.GetChildren();
foreach (var key in values)
{
foreach (var item in key.GetChildren())
{
// get the correct name of the config node
var tenantId = item.Key.Split(':').Last();
// and the connection string
var connectionString = item.Value;
// create the OptionsBuilder and configure it to use SQL server with the connection string
var builder = new DbContextOptionsBuilder();
builder.UseSqlServer(connectionString);
// and register it with the factory
tenantContextFactory.RegisterTenant(tenantId, builder.Options);
}
}
// register the factory with the DI container
services.AddInstance(typeof(ITenantContextFactory), tenantContextFactory);
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以将工厂作为服务注入任何需要它的控制器或服务,并正确地实例化所需的上下文.
到现在为止还挺好.还存在以下问题:
如何集成EF7迁移?(解决了)
尝试添加迁移我收到以下错误:
System.InvalidOperationException:未配置任何数据库提供程序.在设置服务时,通过在DbContext类或AddDbContext方法中覆盖OnConfiguring来配置数据库提供程序.
由于租户数是动态的,我不能直接在DbContext类中指定连接字符串,或使用AddDbContext方法静态注册DbContexts与单个数据库.
当我提供静态连接字符串时,迁移会成功创建,但是当我尝试使用我的动态方法时,这些迁移不会应用于正在使用的数据库,我无法在EF shell中指定连接字符串命令以手动或通过shell脚本执行迁移.我基本上必须为每个租户重写一次配置代码,重新编译然后使用shell命令来执行迁移,这不是一个值得的选择.
解:
要为要使用的每个上下文使用以下代码段来迁移上下文:
using (var context = tenantContextFactory.GetTenantContext<MyContext>(tenantId))
{
context.Database.Migrate();
}
Run Code Online (Sandbox Code Playgroud)
如果架构符合最新迁移,则会自动检查数据库,否则会应用它.
如何集成ASP.NET身份?
需要调整身份验证过程以正确登录用户.
我现在正在使用它,并将在此处发布我的进度更新.
如何在运行时更改租户?
这与之前的问题有关.如何通过编辑配置文件来确保我可以安全地添加或删除租户,而无需重新启动服务?这甚至可能吗?
编辑:
我找到了EF7中迁移问题的解决方案.下一个挑战是ASP.NET身份.
正如许多人所建议的那样,拥有一个数据库会干净得多。请参阅我在讨论中的评论..
数据库中有一个提供者/源表。
然后创建必须接受 SourceId 的 Repo。
public interface IRepository<T>
{
T GetById(int sourceid, int id);
}
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
public TEntity GetById(int sourceId, int id)
{
return _dbContext.Set<TEntity>().Find(sourceId, id);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这需要您基本上在每个表上都有 SourceId。
我知道这不是您正在寻找的答案,但也许是值得考虑的事情。
对我来说,代码非常雄心勃勃,并且维护起来非常复杂。
但我真心希望你能做对!
更新
using(var context = new MyContext(DbHelper.GetConnectionString()))
{
}
public static class DbHelper
{
public static string GetConnectionString()
{
//some logic to get the corrosponding connection string
// which you are wanting this could be based of url
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2293 次 |
| 最近记录: |