I am writing a new application at the moment, although the standard of the company is to use NHibernate (because this standard is for all projects), and instead I use ASP.NET MVC 3 because of its maturity now. I implemented my transactions in controllers (which is supposedly the way you should do this), so this looks like in my root controller:
[TransactionPerRequest]
public class FbsController : Controller
{
}
Then all my controllers inherit from this FbsController. The reason for this is that 90% of all my actions will be sent to the database, so the overhead of creating a transaction and ordering it for the remaining 10% of the actions (which will rarely be performed) are not worth decorating every action [TransactionPerRequest].
What has always offended me relates to NHibernate sessions. In repository classes, this is similar to what I have, although in other projects this is different:
public void Add(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
session.Save(user);
}
}
public void Remove(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
session.Delete(user);
}
}
public User GetById(int userId)
{
using (ISession session = NHibernateHelper.OpenSession())
{
return session.QueryOver<User>()
.Where(c => c.UserID == userId)
.SingleOrDefault();
}
}
So, for most of the functions in my repository, I need to open a session. Is there a way to avoid this behavior, so I don’t need to open a session inside each repository method? This seems a bit controversial, as I usually have to do this for everyone. I was curious that all the other solutions were related to the transaction and session problem that I see clogging up the code in different ways.
Actually, I want my repository methods to look like this:
public void Add(User user)
{
session.Save(user);
}
public void Remove(User user)
{
session.Delete(user);
}
public User GetById(int userId)
{
return session.QueryOver<User>()
.Where(c => c.UserID == userId)
.SingleOrDefault();
}
Everything that is implicitly.
source
share