Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7161739
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T13:37:03+00:00 2026-05-28T13:37:03+00:00

I’m building a multi-tenant web application where for security concerns, we need to have

  • 0

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T13:37:04+00:00Added an answer on May 28, 2026 at 1:37 pm

    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<string, string> settings)
        {
            ConfigureDriver(settings);
        }
    }
    

    Using FluentNHibernate you set the provider like so:

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

    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<Tenant>
    {
        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<Tenant, ISessionFactory> 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<Tenant, ISessionFactory> sessionFactories = 
            new Dictionary<Tenant, ISessionFactory>();
    
        private static readonly object factorySyncRoot = new object();
    
        private string defaultConnectionString = 
            @"Server=(local)\sqlexpress;Database=NHibernateMultiTenancy;integrated security=true;";
    
        private readonly ISessionFactory defaultSessionFactory;
        private readonly ITenantAccessor tenantAccessor;
    
        public NHibernateSessionSource(ITenantAccessor tenantAccessor)
        {
            if (tenantAccessor == null)
                throw new ArgumentNullException("tenantAccessor");
    
            this.tenantAccessor = tenantAccessor;
    
            lock (factorySyncRoot)
            {
                if (defaultSessionFactory != null) return;
    
                var configuration = AssembleConfiguration("default", defaultConnectionString);
                defaultSessionFactory = configuration.BuildSessionFactory();
            }
        }
    
        private Configuration AssembleConfiguration(string name, string connectionString)
        {
            return Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)
                )
                .Mappings(cfg =>
                {
                    cfg.FluentMappings.AddFromAssemblyOf<NHibernateSessionSource>();
                })
                .Cache(c =>
                    c.UseSecondLevelCache()
                    .ProviderClass<HashtableCacheProvider>()
                    .RegionPrefix(name)
                )
                .ExposeConfiguration(
                    c => c.SetProperty(NHibernate.Cfg.Environment.SessionFactoryName, name)
                )
                .BuildConfiguration();
        }
    
        private ISessionFactory GetSessionFactory(Tenant currentTenant)
        {
            ISessionFactory tenantSessionFactory;
    
            sessionFactories.TryGetValue(currentTenant, out tenantSessionFactory);
    
            if (tenantSessionFactory == null)
            {
                var configuration = AssembleConfiguration(currentTenant.Name, currentTenant.ConnectionString);
                tenantSessionFactory = configuration.BuildSessionFactory();
    
                lock (factorySyncRoot)
                {
                    sessionFactories.Add(currentTenant, tenantSessionFactory);
                }
            }
    
            return tenantSessionFactory;
        }
    
        public ISession CreateSession()
        {
            var tenant = tenantAccessor.GetCurrentTenant();
    
            if (tenant == null)
            {
                return defaultSessionFactory.OpenSession();
            }
    
            return GetSessionFactory(tenant).OpenSession();
        }
    }
    

    When we create an instance of NHibernateSessionSource we set up a default SessionFactory to our “default” database.

    When CreateSession() is called we get a ISessionFactory instance. This will either be the default session factory (if the current tenant is null) or a tenant specific session factory. The task of locating the tenant specific session factory is performed by the GetSessionFactory method.

    Finally we call OpenSession on the ISessionFactory instance we have obtained.

    Note that when we create a session factory we set the SessionFactory name (for debugging/profiling purposes) and cache region prefix (for the reasons mentioned above).

    Our IoC tool (in my case StructureMap) wires everything up:

        x.For<ISessionSource>().Singleton().Use<NHibernateSessionSource>();
        x.For<ISession>().HttpContextScoped().Use(ctx => 
            ctx.GetInstance<ISessionSource>().CreateSession());
        x.For<ITenantAccessor>().Use<DefaultTenantAccessor>();
    

    Here NHibernateSessionSource is scoped as a singleton and ISession per request.

    Hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have thousands of HTML files to process using Groovy/Java and I need to
I have a reasonable size flat file database of text documents mostly saved in
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a jquery bug and I've been looking for hours now, I can't
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
We're building an app, our first using Rails 3, and we're having to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.