EntityFramework .net core 中用户特定的连接字符串 [英] User specific connection string in EntityFramework .net core
问题描述
我们正在使用 .net core 和 EntityFramework 开发多租户应用.将有一个已部署的 API 实例,但会有多个 DBS(每个用户一个 DB).那么,根据每个用户的上下文更改数据库连接字符串的最佳策略是什么.
We are developing a multitenant app using .net core and EntityFramework. There will be a single deployed instance of APIs but multiple DBS( one DB per user). So what's the best strategy change DB connection string as per-user context.
推荐答案
在DbContext
的OnConfiguring
方法中设置连接字符串,通过调用UseSqlServer代码>,或任何您的数据库.在此方法中,您需要引用某些将提供特定于用户的连接的服务.为此,IMO,最好的方法是通过
和所有注册的服务.您一定不要忘记通过调用DbContext
类注入一个 IHttpContextAccessor
,然后在 OnConfiguring
中使用它来获取 IHttpContextAccessor
code>HttpContextAddHttpContextAccessor
来注册IHttpContextAccessor
.示例代码:
Set the connection string in the OnConfiguring
method of DbContext
, by calling UseSqlServer
, or whatever your database is. In this method, you need to have a reference to some service that will provide the user-specific connection. For this, IMO, the best way is to inject an IHttpContextAccessor
through the DbContext
class, and, inside OnConfiguring
, use it to obtain the HttpContext
and all the registered services. You must not forget to register IHttpContextAccessor
by a call to AddHttpContextAccessor
.
Sample code:
//MyContext
public class MyContext : DbContext
{
public MyContext(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options)
{
this.HttpContextAccessor = httpContextAccessor;
}
protected IHttpContextAccessor HttpContextAccessor { get; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
var context = this.HttpContextAccessor.HttpContext;
var userService = context.RequestServices<IUserService>();
var user = context.User.Identity.Name;
var connectionString = userService.GetConnectionString(user);
builder.UseSqlServer(connectionString);
base.OnConfiguring(builder);
}
}
//Startup.ConfigureServices
services.AddHttpContextAccessor();
services.AddDbContext<MyContext>();
请注意,IUserService
只是您必须实现的一些服务,它将返回给定用户的连接字符串.
Note that IUserService
is just some service that you must implement that will return the connection string for the given user.
这篇关于EntityFramework .net core 中用户特定的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!