0
votes

I am working on setting up a multi-tenant, seperate database application and have made some good progress from reading this post below on stackoverflow.

Multitenancy with Fluent nHibernate and Ninject. One Database per Tenant

I see two sessions being setup. One is the 'master' session that will be used to get the tenant information and then the tenant session which is specific to the subdomain. I have the app switching nicely to the specified database based on domain and have questions on how to setup the 'master' database session and how to use it.

I tried registering a new session specifically for the master session be get an error regarding having already registered an ISession.

I'm new to nHibernate and not sure the best route to take on this.

NinjectWebCommon.cs

kernel.Bind<WebApplication1.ISessionSource>().To<NHibernateTenantSessionSource>().InSingletonScope();
kernel.Bind<ISession>().ToMethod(c => c.Kernel.Get<WebApplication1.ISessionSource>().CreateSession());
kernel.Bind<ITenantAccessor>().To<DefaultTenantAccessor>();

ITenantAccessor.cs

 public Tenant GetCurrentTenant()
    {
      var host = HttpContext.Current.Request.Url != null ? HttpContext.Current.Request.Url.Host : string.Empty;

      var pattern = ConfigurationManager.AppSettings["UrlRegex"];
      var regex = new Regex(pattern);
      var match = regex.Match(host);

      var subdomain = match.Success ? match.Groups[1].Value.ToLowerInvariant() : string.Empty;
      Tenant tenant = null;

      if (subdomain != null)
      {
        // Get Tenant info from Master DB.
        // Look up needs to be cached
        DomainModel.Master.Tenants tenantInfo;

        using (ISession session = new NHibernateMasterSessionSource().CreateSession())
        {
            tenantInfo = session.CreateCriteria<DomainModel.Master.Tenants>()
                .Add(Restrictions.Eq("SubDomain", subdomain))
                .UniqueResult<WebApplication1.DomainModel.Master.Tenants>();
        }

        var connectionString = string.Format(ConfigurationManager.AppSettings["TenanatsDataConnectionStringFormat"], 
            tenantInfo.DbName, tenantInfo.DbUsername, tenantInfo.DbPassword);

        tenant = new Tenant();
        tenant.Name = subdomain;
        tenant.ConnectionString = connectionString;
      }

      return tenant;
    }

Thanks for you time on this.

1
And what is exactly your question?Remo Gloor
How to setup a 'master' session in addition to the tenant session I have working. Example: Open master session to get tenant information from master DB based on subdomain.Todd

1 Answers

3
votes

Add another session binding and add some condition. E.g.

kernel
    .Bind<ISession>()
    .ToMethod(c => c.Kernel.Get<NHibernateMasterSessionSource>().CreateSession())
    .WhenInjectedInto<TenantEvaluationService>();