Pierre Murasso
Pierre Murasso

Reputation: 601

NHibernate session (and stateless session) and long running application

In the context of a windows web service that's meant to run jobs, we try to reuse the NHibernate DAL we developed for the web application.

For session management we have two options, each one having its advantages and drawbacks:

Stateful session

Stateless Session

Initializing [...] failed to lazily initialize a collection of role: [...], no session or session was closed

Obviously, we cannot update the mappings (they are shared with the web app) with lazy="false", it's gonna be a huge drawback for performances

NHibernate has proven to be good until now, we have successfully used stateful session and NHibernate LINQ it in a web context, with structuremap for dependency injection.

My questions are:

Upvotes: 4

Views: 3234

Answers (2)

Pierre Murasso
Pierre Murasso

Reputation: 601

Problem solved! There were actually a couple of problems.

First one was about instances' scope, and multi-threading:

  • Create a new session for each thread.
  • As soon as the thread finishes its work, clean all the instances attached to the thread. With StructureMap, within the thread, use new HybridLifecycle().FindCache().DisposeAndClear();. It will cause the session attached to the thread to close and dispose.
  • When the lifecycle is thread scoped, StructureMap uses a ThreadStatic variable to keep a reference to the object cache. So the trick is to call StructureMap's ObjectFactory within the thread. Initially, in our application, a main thread was responsible for creating new threads, and call the ObjectFactory. That's the major mistake we did, and were indeed unable to clean the threads once their job was done.

Session type:

  • No need to use a StateLessSession, as soon as the StateFul sessions instantiated are carefully disposed. In our case, StatelessSession have too many drawbacks (cache management is the main)

Important remark: be careful to instantiate NHibernate NHibernate Session Factory only once!

When NHibernate instances are managed carefully, there is no memory leak.

Upvotes: 2

xing
xing

Reputation: 447

It's never a good idea to keep a stateful session open in a long running process.

My suggestion is to redesign your process to separate database related code from non-database related code so any database related operation can be kept within a short-span session.

Upvotes: 0

Related Questions