title: Need a simple example of using nhibernate + unit of work + repository pattern + service layer + ninject
body: <p>I am using </p>
  
  <ul>
  <li>nhibernate + fluent nhibernate</li>
  <li>asp.net mvc 3</li>
  <li>ninject</li>
  </ul>
  
  <p>Currently I am using nhibernate, ninject with the repository pattern and service layers.</p>
  
  <p>So I have this</p>
  
  <h2>ninject</h2>
  
  <pre><code> public class NhibernateSessionFactory
      {
          public ISessionFactory GetSessionFactory()
          {
             ISessionFactory fluentConfiguration = Fluently.Configure()
                                                    .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c =&gt; c.FromConnectionStringWithKey("ConnectionString")))
                                                    .Mappings(m =&gt; m.FluentMappings.AddFromAssemblyOf&lt;Framework.Data.Mapping.TableAMap&gt;().Conventions.Add(ForeignKey.EndsWith("Id")))
                                                    .ExposeConfiguration(cfg =&gt; cfg.SetProperty("adonet.batch_size", "20"))
                                                    .ExposeConfiguration(c =&gt; c.SetProperty("generate_statistics", "true"))
                                                    //.ExposeConfiguration(BuidSchema)
                                                    .BuildSessionFactory();
  
              return fluentConfiguration;
          }
  
          private static void BuidSchema(NHibernate.Cfg.Configuration config)
          {
              new NHibernate.Tool.hbm2ddl.SchemaExport(config).Create(false, true);
          }
  
  
   public class NhibernateSessionFactoryProvider : Provider&lt;ISessionFactory&gt;
      {   
          protected override ISessionFactory CreateInstance(IContext context)
          {
              var sessionFactory = new NhibernateSessionFactory();
              return sessionFactory.GetSessionFactory();
          }
      }
  
  
     public class NhibernateModule : NinjectModule
      {
          public override void Load()
          {
              Bind&lt;ISessionFactory&gt;().ToProvider&lt;NhibernateSessionFactoryProvider&gt;().InSingletonScope();
              Bind&lt;ISession&gt;().ToMethod(context =&gt; context.Kernel.Get&lt;ISessionFactory&gt;().OpenSession()).InRequestScope()
                                                                                        .OnActivation(StartTransaction)
                                                                                        .OnDeactivation(CommitTransaction);
          }
  
          public void CommitTransaction(ISession session)
          {
  
              if (session.Transaction.IsActive)
              {
                  session.Transaction.Commit();
              }
  
          }
  
          public void StartTransaction(ISession session)
          {
              if (!session.Transaction.IsActive)
              {
                  session.BeginTransaction();
              }
          }
      }
  </code></pre>
  
  <p>So I make my nhibernate session factory once for the lifetime of the application then I use it give me sessions when I need it.</p>
  
  <p>One Start of transaction I start a transaction and at the end I close the transaction.</p>
  
  <p>The reason why I did this was because when I was using the nhibernate profiler I would get alot of warnings about using <a href="http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions" rel="nofollow noreferrer"> implicit transactions</a>  This sort of put a bandaid on the problem but never really fixed it(it cut down the number but anything lazy loaded still got this problem).</p>
  
  <h2>an example repo</h2>
  
  <pre><code> public class CalendarRepo : ICalendarRepo
      {
          private readonly ISession session;
  
          public CalendarRepo(ISession session)
          {
              this.session = session;
          }
  
          public List&lt;CalendarAppointment&gt; RepeatingAppointments(int repeatingId)
          {
  
              List&lt;CalendarAppointment&gt; calendarAppointments = session.Query&lt;CalendarAppointment&gt;().Where(x =&gt; x.RepeatingId == repeatingId &amp;&amp; x.RepeatingId != 0)
                                                                                                   .Take(QueryLimits.Appointments)
                                                                                                    .ToList();
              return calendarAppointments;
  
          }
      }
  </code></pre>
  
  <h2>service layer</h2>
  
  <pre><code> public class CalendarService : ICalendarService
      {
          private readonly ICalendarRepo calendarRepo;
  
  
          public CalendarService(ICalendarRepo calendarRepo)
          {
              this.calendarRepo = calendarRepo;
  
  
          }
          // normally would return something and take in params
           public void SampleServiceMethod()
          {
              // do some checks if needed
              // call up the repository
              // call commit 
              // done.
          }
      }
  </code></pre>
  
  <p>So that is basically what I have. </p>
  
  <p>I would like to use the unit of work pattern so I get more things commiting and do things properly with the transactions(<a href="https://stackoverflow.com/questions/6245708/how-to-wrap-lazy-loading-in-a-transaction/7060456#7060456">as right now I been told that I am doing them not quite right</a>)</p>
  
  <p>So I am looking for a simple example on how to get them all to work together and find out how much I need to change of what I got so far.</p>
  
  <p>Most of the tutorials I seen are more complex then I would like. Most do TDD and make generic repositories what is good but before I get to that stage I would like to see a tutorial that does thing simply even if it is repeating code.</p>
  
  <p><strong>Edit</strong></p>
  
  <hr/>
  
  <p>So I been playing around with it and came up with this very very simple example. I am not sure if I am doing it right.</p>
  
  <p><strong>Ninject</strong></p>
  
  <pre><code>/// &lt;summary&gt;
  /// Load your modules or register your services here!
  /// &lt;/summary&gt;
  /// &lt;param name="kernel"&gt;The kernel.&lt;/param&gt;
  private static void RegisterServices(IKernel kernel)
  {
  
     kernel.Bind&lt;ISessionFactory&gt;().ToProvider&lt;NhibernateSessionFactoryProvider&gt;().InSingletonScope();
     kernel.Bind&lt;ISession&gt;().ToMethod(context =&gt; context.Kernel.Get&lt;ISessionFactory&gt;().OpenSession()).InRequestScope();
     kernel.Bind&lt;ITable1Repo&gt;().To&lt;Table1Repo&gt;();
     kernel.Bind&lt;ITable1Service&gt;().To&lt;Table1Service&gt;();
     kernel.Bind&lt;IUnitofWork&gt;().To&lt;UnitofWork&gt;();
  
  }  
  </code></pre>
  
  <p>The nhibernate factory class is shown in orginal post.</p>
  
  <pre><code> // Controller
    public class Default1Controller : Controller
      {
          private readonly ITable1Service table1Service;
          //
          // GET: /Default1/
          public Default1Controller(ITable1Service table1Service)
          {
              this.table1Service = table1Service;
          }
  
          public ActionResult Index()
          {
              table1Service.Save();
              return View();
          }
  
      }
  </code></pre>
  
  <p><strong>// domain</strong></p>
  
  <pre><code>  public class Table1
      {
          public virtual int Id { get; private set; }
          public virtual string C1 { get;  set; }
          public virtual string C2 { get; set; }
      }
  </code></pre>
  
  <p><strong>// Fluent Mapping</strong></p>
  
  <pre><code>  public class Table1Mapping : ClassMap&lt;Table1&gt;
      {
          public Table1Mapping()
          {
              Id(x =&gt; x.Id);
              Map(x =&gt; x.C1);
              Map(x =&gt; x.C2);
          }
      }
  </code></pre>
  
  <p><strong>//Repo</strong></p>
  
  <pre><code> public class Table1Repo : unitofwork.Models.Repository.ITable1Repo
      {
          private readonly ISession session;
  
          public Table1Repo(ISession session)
          {
              this.session = session;
          }
  
          public void Create(Table1 tbl1)
          {
              session.Save(tbl1);
          }
      }
  </code></pre>
  
  <p><strong>// service layer</strong></p>
  
  <pre><code> public class Table1Service : unitofwork.Models.Service.ITable1Service
      {
          private readonly ITable1Repo table1Repo;
          private readonly IUnitofWork unitOfWork;
          public Table1Service(ITable1Repo table1Repo, IUnitofWork unitOfWork)
          {
              this.table1Repo = table1Repo;
              this.unitOfWork = unitOfWork;
          }
  
          public void Save()
          {
              Table1 a = new Table1();
              a.C1 = "test";
              a.C2 = "test2";
  
              table1Repo.Create(a);
              unitOfWork.Commit();
  
  
          }
      }
  </code></pre>
  
  <p><strong>// Unit of work</strong></p>
  
  <pre><code>public class UnitofWork : unitofwork.Models.IUnitofWork
      {
          private readonly ITransaction transaction;
          private readonly ISession session;
  
          public UnitofWork(ISession session)
          {
              this.session = session;
              session.FlushMode = FlushMode.Auto;
              transaction = session.BeginTransaction(IsolationLevel.ReadCommitted);
          }
  
          public void Commit()
          {
              if (!transaction.IsActive)
              {
                  throw new InvalidOperationException("Oops! We don't have an active transaction");
              }
              transaction.Commit();
          }
  
          public void Rollback()
          {
              if (transaction.IsActive)
              {
                  transaction.Rollback();
              }
          }
  
          public void Dispose()
          {
              if (session.IsOpen)
              {
                  session.Close();
              }
          }
      }
  </code></pre>