As above really.
Note that when supplying an IDbConnection
to OpenSession()
, you will not be able to use the 2nd level cache.
See https://forum.hibernate.org/viewtopic.php?f=25&t=959178
... "This is not a bug. If you are managing your own connections, NHibernate disables the use of second-level cache for the session to be safe."...
An ISessionFactory.OpenSession()
can be supplied with a IDbConnection
.
Another option is to implement a IConnectionProvider
wich would create appropriate IDbConnection
instances depending upon some condition (which has to be global, thus rendering this solution not very clean).
Well, it may be tricky but and I think it should not be done, but here's the idea:
var cfg = new Configuration(); // Get a new NHibernate Configuration
cfg.SetProperty("connection.connection_string", yourConnectionString); // Alter the property
cfg.Configure(); // Configure with this configuration
var sf = cfg.BuildSessionFactory(); // Get a new ISessionFactory
I don't know if this is the best method, but may work. You could as well have 2 configuration xml files and do this:
var cfg = new Configuration("hibernate1.cfg.xml"); // OR
var cfg = new Configuration("hibernate2.cfg.xml");
Responding to the comments, you can have several session factories initialized and ready for use, but that's not exactly "change the connection string". Then choose the one you need. The costly part is creating the Configuration object and calling Configure().
There's as well NHibernate Burrow library, that manages several sessions at the same time and chooses the right one depending on the entity.
var session = new BurrowFramework().GetSession(); // default session
var session = new BurrowFramework().GetSession(typeof(Entity)); // session that manages Entity class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With