Multitenancy with Fluent nHibernate and Ninject. One Database per Tenant

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

I'm building a multi-tenant web application where for security concerns, we need to have one instance of the database per tenant. So I have a MainDB for authentication and many ClientDB for application data.

I am using Asp.net MVC with Ninject and Fluent nHibernate. I have already setup my SessionFactory/Session/Repositories using Ninject and Fluent nHibernate in a Ninject Module at the start of the application. My sessions are PerRequestScope, as are repositories.

My problem is now I need to instanciate a SessionFactory (SingletonScope) instance for each of my tenants whenever one of them connects to the application and create a new session and necessary repositories for each webrequest. I'm puzzled as to how to do this and would need a concrete example.

Here's the situation.

Application starts : The user of TenantX enters his login info. SessionFactory of MainDB gets created and opens a session to the MainDB to authenticate the user. Then the application creates the auth cookie.

Tenant accesses the application : The Tenant Name + ConnectionString are extracted from MainDB and Ninject must construct a tenant specific SessionFactory (SingletonScope) for that tenant. The rest of the web request, all controllers requiring a repository will be inject with a Tenant specific session/repository based on that tenant's SessionFactory.

How do I setup that dynamic with Ninject? I was originally using Named instance when I had multiple databases but now that the databases are tenant specific, I'm lost...

回答1:

After further research I can give you a better answer.

Whilst it's possible to pass a connection string to ISession.OpenSession a better approach is to create a custom ConnectionProvider. The simplest approach is to derive from DriverConnectionProvider and override the ConnectionString property:

public class TenantConnectionProvider : DriverConnectionProvider {     protected override string ConnectionString     {         get         {             // load the tenant connection string             return "";         }     }      public override void Configure(IDictionary settings)     {         ConfigureDriver(settings);     } },>

Using FluentNHibernate you set the provider like so:

var config = Fluently.Configure()     .Database(         MsSqlConfiguration.MsSql2008             .Provider()     )

The ConnectionProvider is evaluated each time you open a session allowing you to connect to tenant specific databases in your application.

An issue with the above approach is that the SessionFactory is shared. This is not really a problem if you are only using the first level cache (since this is tied to the session) but is if you decide to enable the second level cache (tied to the SessionFactory).

The recommended approach therefore is to have a SessionFactory-per-tenant (this would apply to schema-per-tenant and database-per-tenant strategies).

Another issue often overlooked is that although the second level cache is tied to the SessionFactory, in some cases the cache space itself is shared (reference). This can be resolved by setting the "regionName" property of the provider.

Below is a working implementation of SessionFactory-per-tenant based on your requirements.

The Tenant class contains the information we need to set up NHibernate for the tenant:

public class Tenant : IEquatable {     public string Name { get; set; }     public string ConnectionString { get; set; }      public bool Equals(Tenant other)     {         if (other == null)             return false;          return other.Name.Equals(Name) && other.ConnectionString.Equals(ConnectionString);     }      public override bool Equals(object obj)     {         return Equals(obj as Tenant);     }      public override int GetHashCode()     {         return string.Concat(Name, ConnectionString).GetHashCode();     } }

Since we'll be storing a Dictionary,> we implement the IEquatable interface so we can evaluate the Tenant keys.

The process of getting the current tenant is abstracted like so:

public interface ITenantAccessor {     Tenant GetCurrentTenant(); }  public class DefaultTenantAccessor : ITenantAccessor {     public Tenant GetCurrentTenant()     {         // your implementation here          return null;     } }

Finally the NHibernateSessionSource which manages the sessions:

public interface ISessionSource {     ISession CreateSession(); }  public class NHibernateSessionSource : ISessionSource {     private Dictionary sessionFactories =          new Dictionary();      private static readonly object factorySyncRoot = new object();      private string defaultConnectionString  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!