In this question I asked about the duration of the NHibernate session. I use a desktop application, but with a separation between the client and the server, so the conclusion is that I will use one session for each server request, since all the magic of NHibernate happens on the server side.
Now my problem is how to handle this. I had problems before loading the reference data when the session was prematurely closed. The problem is that when debugging, I see the following in my reference classes - so the reference data is not yet loaded:
base {NHibernate.HibernateException} = {"Initialization [MyNamespace.Foo # 14] - failed to lazily initialize the role collection: MyNamespace.Foo.Bars, session or session closed"}
From what I understand, it does not load everything, even if I commit a transaction. So, I found out that I need to keep the session open for a while, but for how long?
My question is mainly if I handle all my life correctly, or what I have to change to be on the right track. Honestly, I donโt see how this could be wrong, so I would really like it to call a function to provide reference data. I do not use lazy loading, so I thought they would be downloaded immediately.?
Current architecture: using the class "service behavior" that performs the transaction. This is IDisposable, therefore the service itself uses a using-sentence around it. NHibernateSessionFactory provides a static factory, which therefore will be reused.
// This is the service - the function called "directly" through my WCF service. public IList<Foo> SearchForFoo(string searchString) { using (var serviceBehavior = new FooServiceBehavior(new NhibernateSessionFactory())) { return serviceBehavior.SearchForFoo(searchString); } } public class FooServiceBehavior : IDisposable { private readonly ISession _session; public FooServiceBehavior(INhibernateSessionFactory sessionFactory) { _session = sessionFactory.OpenSession(); } public void Dispose() { _session.Dispose(); } public IList<Foo> SearchForFoo(string searchString) { using (var tx = _session.BeginTransaction()) { var result = _session.CreateQuery("from Foo where Name=:name").SetString("name", searchString).List<Name>(); tx.Commit(); return result; } }
stiank81
source share