0
votes

I am attempting to speed up some web service calls and suspect opening many NHibernate connections is the problem. I am aware that opening a new connection to SQL server is very time consuming and expensive. But I thought NHibernate would preserve a single connection (therefore only needing to open it once) even if I opened an nhibernate session in many places.

So here's a few different parts to this question:

  • if I create a session and dispose of it, then create it again, does it take the same time to load the second time around, or is the sql server connection still in the background for use? like this:
    using (var session = new SessionFactory.OpenSession()) {... };
    using (var session2 = new SessionFactory.OpenSession()) {.. };
  • if I create a session within a using statement, and then create another one within that statment (without disposing it) would it not need to spin up a whole other sql server connection in the background? like this:
    using (var session = new SessionFactory.OpenSession()) 
    {
        using (var session2 = new SessionFactory.OpenSession()) {.. };
    };
  • lastly, are the sql server connections preserved across web service calls? ie if I open a session on web service request call #1, would web service request call #2 be much faster since a hidden connection is sitting around somewhere in the background which it will pick up and use?

I am aware that it's probably best in most cases to just use one session, but a very large program was written with many new sessions open all over and I'm trying to figure out whether it would really save much performance to re-write this or not.

Thanks!

1

1 Answers

1
votes

NHibernate most likely will not work if you open session within session. Connections are usually pooled and once it is not used it is returned to the pool. If pool does not have any connections available, then new one is created. I suggest look into query optimizations and caching. Connections will not speed things up.