Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate transaction management in ASP.NET MVC - how should it be done?

I am writing a simple ASP.NET MVC using session per request and transaction per request patterns (custom HttpModule). It seems to work properly, but.. the performance is terrible (a simple page loads ~7 seconds). For every http request, graphical resources incuding (all images on the site) a transaction is created and that seems to delay the loading times (without the transactions loading times per one image are ~1-10 ms with transactions they are over 1 second). What is the proper way to manage transactions in ASP.NET MVC + NH stack?

When i've put all transactions into my repository methods, for some obscure reasons I got 'implicit transactions' warning in NHProf (the SQL statements were executed outside transaction, even that in code session.Save()/Update()/etc methods were invoked within transaction 'using' scope and before transaction.Commit() call) BTW are implicit transactions really bad?

like image 355
adrin Avatar asked Apr 05 '10 22:04

adrin


2 Answers

The implicit transactions occurs when you do not place your statements in a transaction. The implicit is that if you don't explicitly declare a transaction each one of your statements runs in its own transaction. So yeah it's bad. That bad? I don't know enough about what you're working on to judge.

I do the same thing that you're doing with session per request but I do not get anywhere near the same performance numbers. I would recommend looking into turning on log4net for NHibernate and see what it's doing. Your application should only be creating the session factory and proxy factories one time (managing the session factory would be one of the few places I would use a singleton). That's really the only thing I can think of that might cause it.

like image 121
Min Avatar answered Nov 10 '22 01:11

Min


There are a couple issues here:

First, regarding your performance issues. Are you making sure that the ISessionFactory is only instantiated once? It's a very expensive object to create, so it should probably be a singleton in your web app that's created on Application_Start, rather than in Application_BeginRequest. My guess as to why you're getting such poor performance is that you're creating a new ISessionFactory per request rather than once for the entire application.

Second, regarding implicit transactions, they're not that bad, but from the way you're describing your code you shouldn't be getting these errors. Are you sure you're executing your calls within a transaction? It's possible that you're accessing some lazy-load properties from the .aspx and .ascx pages that may execute outside of your transaction.

like image 30
Kevin Pang Avatar answered Nov 10 '22 00:11

Kevin Pang