title: NHibernate Sessions + Transactions Using ASP.NET MVC 3
body: <p>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:</p>
  
  <pre><code>[TransactionPerRequest]
  public class FbsController : Controller
  {
  
  }
  </code></pre>
  
  <p>Then all my controllers inherit from this <code>FbsController</code>.  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 <code>[TransactionPerRequest]</code>.</p>
  
  <p>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:</p>
  
  <pre><code>    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&lt;User&gt;()
                  .Where(c =&gt; c.UserID == userId)
                  .SingleOrDefault();
          }
      }
  </code></pre>
  
  <p>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 &amp; session issue that I see littered around code in a variety of ways.</p>
  
  <p>Realistically I want my repository methods to look like the following:</p>
  
  <pre><code>    public void Add(User user)
      {
          session.Save(user);
      }
  
      public void Remove(User user)
      {
          session.Delete(user);
      }
  
      public User GetById(int userId)
      {
          return session.QueryOver&lt;User&gt;()
              .Where(c =&gt; c.UserID == userId)
              .SingleOrDefault();
      }
  </code></pre>
  
  <p>With everything being dealt with implicitly.</p>