Is there a way to reuse a NHibernate SessionFactory for multiple databases?

我只是一个虾纸丫 提交于 2019-12-09 23:31:37

问题


Like the title says, is there a way to "reuse" a SessionFactory for multiple databases? Since instantiating the SessionFactory takes time, I wonder if it would be possible to pool these instances and reuse them, changing only the connection/database name. Obviously, first level cache would be cleared, but I am trying to avoid the penalty involved in instantiating the factory itself.

The background is that I can have several small "pluggable" databases with exactly the same schema, so there is no need for NHibernate to rebuild all mappings every time.


回答1:


You can dynamically create Session instances from the same session factory for different databases by first opening a standard ADO.NET Connection object appropriate for the target database and passing it to the NH SessionFactory instance like this:

    var connection = new SqlConnection("target DB connection string");
    var session = sessionFactory.OpenSession(connection);
    CurrentSessionContext.Bind(session);

I recommend you use a Dependency Injection container to control the lifetime and disposal of the ADO.NET connection instance instead of creating it directly as shown in the simplified code shown above.

Another gotcha is that NHibernate performs database access when the SessionFactory instance is spun up so you need to either provide a valid connection string in the hibernate.cfg.xml file or dynamically inject that into the session factory configuration logic.

UPDATE:

Groo provided a link to a great post on dynamically switching databases in NHibernate. Follow the advice in that post rather than doing something like the sample code shown above.



来源:https://stackoverflow.com/questions/12745046/is-there-a-way-to-reuse-a-nhibernate-sessionfactory-for-multiple-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!