Skip to content

Instantly share code, notes, and snippets.

@dealproc
Last active March 17, 2019 07:11
Show Gist options
  • Save dealproc/ebea6c3ee3223b66bac4b20bd82c02a5 to your computer and use it in GitHub Desktop.
Save dealproc/ebea6c3ee3223b66bac4b20bd82c02a5 to your computer and use it in GitHub Desktop.
Multi-Tenant Solutions - NHibernateMultiTenantSessionSource.cs
public class NHibernateMultiTenantSessionSource : ISessionSource {
#region Static Members and Constructor.
static readonly object _FactorySyncRoot = new object();
static readonly ConcurrentDictionary<string, ISessionFactory> _SessionFactories = new ConcurrentDictionary<string, ISessionFactory>();
#endregion
readonly IConfigurationReader _configurationManager;
readonly IAccountAccessor _accountAccessor;
readonly string _connectionStringModel;
public NHibernateMultiTenantSessionSource(IConfigurationReader configurationManager, IAccountAccessor accountAccessor) {
_configurationManager = configurationManager;
_accountAccessor = accountAccessor;
_connectionStringModel = _configurationManager.GetConnectionString("{Your tenant storage medium connection string template, whatever that is}");
}
public ISession CreateSession() {
var account = _accountAccessor.GetCurrentAccount();
return account != null ? GetSessionFactory(account).OpenSession() : null;
}
private ISessionFactory GetSessionFactory(Account account) {
ISessionFactory accountSessionFactory;
lock (_FactorySyncRoot) {
if (_SessionFactories.TryGetValue(account.GUID, out accountSessionFactory)) {
return accountSessionFactory;
}
var cfg = BuildConfiguration(account);
accountSessionFactory = cfg.BuildSessionFactory();
_SessionFactories.TryAdd(account.GUID, accountSessionFactory);
return accountSessionFactory;
}
}
private Configuration BuildConfiguration(Account account) {
// build up whatever you need here to connect to your store of choice
return config;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment