Pavlo
Pavlo

Reputation: 397

NHibernate + threads

I have nearly such code:

public class WCFService
{
    public OperationResult Create(...)
    {
        List<SomeClass> classList = new List<SomeClass>();//Items are got from db using       NHibernate
        ...
        Thread t = new Thread(delegate () { 
            foreach ( item in classList)
            {
                Method(item);
            }
        }
    ...
    return new OperationResult();
    }

    public void Method ( List<SomeClass> list) //doesn't use NHibernate Session
    {
    Conslole.Writeline(list.ToString());
    }

}

void main()
{
    WCFService service = new WCFService();
    service.Create(...);
}

After execution in console output there are only part of List. I think Method can't get access to elements of list. When debugging there is such message instead of variable value : "Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation". Or LazyInitialization Exception "Could not initialize proxy - no Session". Is problem in NHibernate session or something else? And how can I solve it? Method is in separate thread because it takes too much time, and result of creation need to be returned as fast as possible.

Upvotes: 0

Views: 527

Answers (1)

Thilak Nathen
Thilak Nathen

Reputation: 1333

You get the LazyInitialization exception because the method is trying to access a property which is not initialized. By default NH associations are lazy loaded, so upon access to the property, NH tries to load the data from the session, which of course by that time is long gone and disposed of.

A few options:

  1. Eager load the associations in your mapping with 'lazy=false'
  2. Eager load the associations in your query with 'FetchMode=join'
  3. Manually do the loading. After you get your entities, access the properties to ensure they are loaded (or use NHibernateUtil.Initialize() on the associations).
  4. Do something like this http://trentacular.com/2009/08/how-to-use-nhibernate-lazy-initializing-proxies-with-web-services-or-wcf/

Upvotes: 1

Related Questions