EntityFramework .net核心中的用户特定的连接字符串 [英] User specific connection string in EntityFramework .net core

查看:91
本文介绍了EntityFramework .net核心中的用户特定的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用.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.

推荐答案

通过调用UseSqlServer或任何数据库,在DbContextOnConfiguring方法中设置连接字符串.在这种方法中,您需要参考一些将提供用户特定连接的服务.为此,IMO最好的方法是通过DbContext类注入IHttpContextAccessor,然后在OnConfiguring内部使用它获取HttpContext和所有已注册的服务.您一定不要忘记通过调用AddHttpContextAccessor来注册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核心中的用户特定的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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