Skip to content

Instantly share code, notes, and snippets.

@dealproc
Last active March 17, 2019 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dealproc/d49ee75365ecf408b8567c017b713d46 to your computer and use it in GitHub Desktop.
Save dealproc/d49ee75365ecf408b8567c017b713d46 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