有没有一种方法可以为多个数据库重用NHibernate SessionFactory? [英] Is there a way to reuse a NHibernate SessionFactory for multiple databases?

查看:108
本文介绍了有没有一种方法可以为多个数据库重用NHibernate SessionFactory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题中所说的那样,有没有办法为多个数据库重用" SessionFactory?由于实例化SessionFactory需要花费时间,因此我想知道是否有可能合并这些实例并重用它们,而仅更改连接/数据库名称.显然,第一级缓存将被清除,但我正在努力避免实例化工厂本身所涉及的损失.

背景是我可以拥有几个具有完全相同模式的小型可插入"数据库,因此NHibernate不需要每次都重建所有映射.

解决方案

您可以通过首先打开适用于目标数据库的标准ADO.NET Connection对象,从同一会话工厂为不同的数据库动态创建Session实例.并将其传递给NH SessionFactory实例,如下所示:

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

我建议您使用依赖关系注入"容器来控制ADO.NET连接实例的寿命和处置,而不要像上面显示的简化代码中所示直接创建它.

另一个难题是,在启动SessionFactory实例时,NHibernate执行数据库访问,因此您需要在hibernate.cfg.xml文件中提供有效的连接字符串,或者将其动态注入会话工厂配置逻辑中. /p>

更新:

Groo在链接到一篇很棒的帖子上提供了一个链接在NHibernate中动态切换数据库.遵循该文章中的建议,而不要像上面显示的示例代码那样做.

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.

解决方案

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.

这篇关于有没有一种方法可以为多个数据库重用NHibernate SessionFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆