I'm writing a new application at the moment, although company standard is to use NHibernate (because that's standard across all projects), and instead I'm using ASP.NET MVC 3 due to its maturity now. I've implemented my transactions in the controllers (which supposedly is the way you're supposed to do it), so it looks like this in my root controller:
[TransactionPerRequest]
public class FbsController : Controller
{
}
Then all my controllers inherit from this FbsController. The reason this is done is because 90% of all my actions will be going off to the database, so the overhead for creating a transaction and disposing of it for the remainder 10% of actions (which will rarely be executed) isn't worth decorating each action with [TransactionPerRequest].
The thing that's always stumped me is in regards to NHibernate sessions. In the repository classes this along the lines of something I have, although this is different in other projects:
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 then for the majority of functions in my repository I'm having to open a session. Is there any way of avoiding this behaviour so I don't have to open a session inside each and every repository method? It seems a bit counter-intuitive as I'll usually have to do it for every single one. I was wondering what everyone else's solution was to the transaction & session issue that I see littered around code in a variety of ways.
Realistically I want my repository methods to look like the following:
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();
}
With everything being dealt with implicitly.