Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change NHibernate's connection string per HTTP request?

As above really.

like image 650
John_ Avatar asked Jan 29 '09 10:01

John_


3 Answers

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."...

like image 127
gurra777 Avatar answered Oct 05 '22 10:10

gurra777


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).

like image 32
Anton Gogolev Avatar answered Oct 05 '22 09:10

Anton Gogolev


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
like image 25
Marc Climent Avatar answered Oct 05 '22 10:10

Marc Climent