Alert: More than one session per request
Using more than one session per request is generally a bad practice. Here is why:
- Each session has its own database connection. Using more than one session means using more than one database connection per request, resulting in additional strain on the database and slower overall performance.
- Typically we expect the session to keep track of our entities. When we have a multiple sessions, each session is not aware of the entities that tracked by the other session and might have to query the database again for its current state or have to issue an unnecessary update.
- Having more than a single session also mean that we can't take advantage on NHibernate's Unit of Work and have to manually manage our entities' change tracking and we might end up with multiple instances of the same entities in the same request (which using a single session for the whole request would prevent).
- Having more than one session means that the ORM have more work to do. In most cases, this is unnecessary and should be avoided.
- You can no longer take advantage of features scoped to the session, such as the first level cache.
It's usually recommended to use one session per request. You should investigate the Session Per Request pattern.
Typically this situation results from micromanaging the session, meaning that we open the session just before the query and close it immediately after the query or operation is executed. For example, see the following code:
public T GetEntity<T>(int id) { using (var session = sessionFactory.OpenSession()) { return session.Get<T>(id); } }
It's strongly recommended to use an ambience / contextual session, that will be the same across the entire request, such as the following code:
public T GetEntity<T>(int id) { var session = sessionFactory.GetCurrentSession(); return session.Get<T>(id); }
This code make use of the current session, so multiple calls to this method will always use the current session, and not open a new one.