2011-05-27 84 views
0

我想使用流暢的NHibernate與ASP.NET MVC 3,我似乎無法找到一個教程,解釋如何讓它全部配置ASP.NET MVC。我主要想知道在什麼地方放置ISession構建函數,以及在需要時如何調用它。我看到了很多不同的實現,但沒有一個指定他們放置代碼的位置。所以,如果任何人都可以解釋如何讓它全部配置爲使用MVC 3或非常詳細的教程,那將不勝感激。Fluent Nhibernate

+0

你在做任何依賴注入? – 2011-05-27 20:29:27

+0

嗯,我想使用StructureMap,但我只是開始設置一切,並開始與流利NHibernate的第一。但是如果我需要首先設置StructureMap以使其更容易,那麼我可以做到這一點。林非常新嘗試像編碼企業,我很困惑。 LOL – vol4life27 2011-05-27 20:30:39

+0

我不確定是否有關於如何入門的真正教程,但這是我熟悉的堆棧。實際上,我現在正在查看代碼,你可能需要開始,但是它的代碼很多,所以我在辯論我應該把它放在哪裏 – 2011-05-27 20:35:11

回答

1

你可以看看S#arp Architecture。 這是一個非常堅實的架構框架,與ASP.NET MVC & NHibernate一起工作。他們有一個體面的文件,並有一些示例項目來看。

http://www.sharparchitecture.net/

1

如果你不使用依賴注入,你可以嘗試這樣的事情

public class MvcApplication : System.Web.HttpApplication 
{ 

    public static ISession CurrentSession 
    { 
     get { return (ISession)HttpContext.Current.Items["current.session"]; } 
     set { HttpContext.Current.Items["current.session"] = value; } 
    } 

    private static ISessionFactory _session_factory; 
    private static object _session_factory_lock = new object(); 

    protected static ISessionFactory CreateSessionFactory() 
    { 

     if (_session_factory != null) return _session_factory; 

     if (ConfigurationManager.ConnectionStrings["DbConnection"] != null) 
     { 
      var conn = ConfigurationManager.ConnectionStrings["DbConnection"]; 
      SqlServerSessionFactoryBuilder fb = new SqlServerSessionFactoryBuilder(conn.ConnectionString); 
      _session_factory = fb.GetSessionFactory(); 
      return _session_factory; 
     } 

     throw new Exception("Cannot build session factory, connection string is not defined."); 

    } 


    public MvcApplication() 
    { 
     _session_factory = CreateSessionFactory(); 

     BeginRequest += delegate 
     { 

      try 
      { 
       CurrentSession = _session_factory.OpenSession(); 
      } 
      catch (FluentConfigurationException ex) 
      { 
       logger.FatalException(string.Format("Error configuring the database {0}", ex.Message), ex); 

      } 

     }; 


     EndRequest += delegate 
     { 
      if (CurrentSession != null) 
      { 
       if (CurrentSession.Transaction != null && CurrentSession.Transaction.IsActive) 
       { 
        logger.Error("Rolling back uncommited transaction"); 
        CurrentSession.Transaction.Rollback(); 
       } 
       else 
       { 
        CurrentSession.Flush();   
       } 
       CurrentSession.Close(); 
      } 
     }; 

     Error += delegate 
     { 
      var error = this.Server.GetLastError(); 
      logger.ErrorException(string.Format("Unhandled error : {0}", error.Message), error); 
     }; 
    } 

    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     RegisterRoutes(RouteTable.Routes); 


    } 

}