Last active
March 17, 2019 07:11
-
-
Save dealproc/ebea6c3ee3223b66bac4b20bd82c02a5 to your computer and use it in GitHub Desktop.
Multi-Tenant Solutions - NHibernateMultiTenantSessionSource.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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