Is there a way to reuse a NHibernate SessionFactor

2019-04-13 10:01发布

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条回答
别忘想泡老子
2楼-- · 2019-04-13 10:47

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.

查看更多
登录 后发表回答