简体   繁体   English

在运行时从子域设置EF ConnectionString以进行多租户设置

[英]Set EF ConnectionString at runtime from subdomain for multi-tenancy setup

Currently, my DbContext class has this code: 当前,我的DbContext类具有以下代码:

public ApplicationDbContext()
    : base("DefaultConnection", throwIfV1Schema: false)
{
}

public static ApplicationDbContext Create()
{
    return new ApplicationDbContext();
}

What I'd like to do, is inspect the subdomain and use that for the database name, so something like http://abc.mysite.com/ would use a connection string with database name abc . 我想做的是检查子域并将其用作数据库名称,因此类似http://abc.mysite.com/东西将使用数据库名称为abc的连接字符串。

But how do I manipulate the value of "DefaultConnection" in the constructor? 但是,如何在构造函数中操纵"DefaultConnection"的值?

DBContext will take a name or a connection string in its constructor. DBContext将在其构造函数中使用名称或连接字符串。 That constructor is not usually exposed if you have a generated model. 如果您具有生成的模型,则通常不会公开该构造函数。

You can use a partial class to expose that constructor: 您可以使用部分类来公开该构造函数:

public partial class DataEntities
{
        public DataEntities(string connectionString) : base(connectionString)
        {   
        }
}

I have done that before. 我以前做过。 My project was set up for DI with Castle Windsor and one of my IWindsorInstaller s was DataAccessInstaller responsible for registering, among other classes like repositories, my database context and here is the relevant code: 我的项目是使用Castle WindsorDI设置的,我的IWindsorInstaller之一是DataAccessInstaller负责在诸如存储库的其他类中注册我的数据库上下文,以下是相关代码:

container.Register(Component
               .For<MyDatabaseContext>().Forward<DbContext>()
               .ImplementedBy<MyDatabaseContext>()
               .LifestylePerWebRequest()
               .UsingFactoryMethod(context =>
               {
                 return MyDatabaseContextFactory.Create(HttpContext.Current.Request.Url);
               }));

You can have several connection strings set up in your web.config matching your domain. 您可以在web.config中设置多个与您的域匹配的连接字符串。

My context factory implementation: 我的上下文工厂实现:

public static class MyDatabaseContextFactory
{
    public static MyDatabaseContext Create(Uri uri)
    {
        return new MyDatabaseContext(uri.GetTopDomain());
    }
}

If you just have a simple project and don't even have DI, you can still make use of a factory that finds out what the website use and instantiates a database context with the appropriate connection string. 如果您只有一个简单的项目,甚至没有DI,您仍然可以使用工厂来查找网站使用的内容,并使用适当的连接字符串实例化数据库上下文。

Needless to say, your current database context constructor doesn't have to change. 不用说,您当前的数据库上下文构造函数不必更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM