NHibernate Connection Pooling

2019-02-24 10:58发布

问题:

I am considering using Fluent NHibernate for a new application with SQL Server 2008 and I am having trouble understanding the connection handling behavior I am seeing.

I am monitoring connections using sp_who2 and here is what I see:

  1. When the SessionFactory is created, a single connection is opened. This connection seems to stay open until the app is killed.

  2. No connection is opened when a new session is opened. (That's ok, I understand NHibernate waits until the last moment to create database connections).

  3. No new connection is opened even when I run a query through NHibernate. I must assume it is using the connection created when the SessionFactory was created, which is still open. I set a breakpoint after the query (before the session was closed), and no new sessions had appeared in sp_who.

Running an entire app through a single connection is not acceptable (obviously). How can I ensure each ISession gets its own connection? I'm sure there's something obvious I'm missing here...

Thanks in advance.

回答1:

The behaviour that you see is nothing NHibernate specific - Connection pooling is default behaviour in SQL Server.
Even if it may sound awkward at first glance, it actually is a good thing because creating new connections and maintaining them is expensive.
(for more information, see the Wikipedia article about connection pooling)

So there is no need to try to get NH to open a new connection for each session, because reusing existing connections actually improves SQL Server performance.